[英]How does OSReadLittleInt16() translate to Swift?
I want to translate my Obj-C code to Swift. 我想将我的Obj-C代码转换为Swift。
I got these 3 lines in Obj-C: 我在Obj-C中获得了以下3行:
NSData* data = ...
unsigned char* bytes = (unsigned char*) data.bytes;
int16_t delta = OSReadLittleInt16(opticalEncoderBytes, 0);
The first two lines translate to: 前两行转换为:
NSData data = ...
let bytes = UnsafePointer<UInt8>(data.bytes)
The third line is not that easy as I don't know: 第三行并不容易,我不知道:
int16_t
simply translate to Int16
? int16_t
简单地转换为Int16
吗? OSReadLittleInt16
is not available in Swift. OSReadLittleInt16
在Swift中不可用。 Do I need to import something? OSReadLittleInt16
is defined in usr/include/libkern/OSByteOrder.h
OSReadLittleInt16
在usr/include/libkern/OSByteOrder.h
Use .bigEndian
and .littleEndian
使用
.bigEndian
和.littleEndian
let i :Int16 = 1
print("i: \(i)")
let le :Int16 = i.littleEndian
print("le: \(le)")
let be :Int16 = i.bigEndian
print("be: \(be)")
i: 1
我:1
le: 1le:1
be: 256是:256
let data: NSData! = "12345678".dataUsingEncoding(NSUTF8StringEncoding)
let bytes = UnsafePointer<UInt16>(data.bytes)
let ui0 = bytes[0]
let ui1 = bytes[1]
print("ui0: \(String(ui0, radix:16))")
print("ui1: \(String(ui1, radix:16))")
let be0 = bytes[0].bigEndian
let be1 = bytes[1].bigEndian
print("be0: \(String(be0, radix:16))")
print("be1: \(String(be1, radix:16))")
let le0 = bytes[0].littleEndian
let le1 = bytes[1].littleEndian
print("le0: \(String(le0, radix:16))")
print("le1: \(String(le1, radix:16))")
ui0: 3231
ui0:3231
ui1: 3433ui1:3433
be0: 3132
be0:3132
be1: 3334be1:3334
le0: 3231
le0:3231
le1: 3433le1:3433
Note that the default in iOS is little endian. 请注意,iOS中的默认值是little endian。
Here is an alternative approach: OSReadLittleInt16()
is a defined as a macro in <libkern/OSByteOrder.h>
as 这是一种替代方法:
OSReadLittleInt16()
在<libkern/OSByteOrder.h>
定义为宏,如下所示:
#define OSReadLittleInt16(base, byteOffset) _OSReadInt16(base, byteOffset)
The macro is not imported into Swift, but the _OSReadInt16()
function is, so you can do 宏不会导入到Swift中,但
_OSReadInt16()
函数已导入,因此您可以执行
let delta = UInt16(littleEndian: _OSReadInt16(bytes, 0))
A possible advantage is that this works also on odd offsets, even if the architecture allows only aligned memory access. 一个可能的优点是,即使架构仅允许对齐的内存访问,这也适用于奇数偏移量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.