我正在尝试将通过蓝牙连接获得的NSData类型的6字节十六进制转换为适当的整数值。我知道这是Big Endian类型,我需要与小Endian合作。但是,每次我尝试转换它,我都可以提取正确的数据,但结果看起来不对,请参阅下面的游乐场代码:
var newdata = NSData(bytes: [0x26, 0x01, 0x45, 0x01, 0x04, 0x5e, ] as [UInt8], length:6)
//var timeData = newdata.subdataWithRange(NSMakeRange(4,2))
//var heelData = newdata.subdataWithRange(NSMakeRange(2,2))
//var frontData = newdata.subdataWithRange(NSMakeRange(0,2))
var timeData:UInt16 = 0
var heelData:UInt16 = 0
var frontData:UInt16 = 0
//var timeData = data.subdataWithRange(NSMakeRange(4,2))
var timeIn: NSNumber = NSNumber(unsignedShort: 0)
newdata.getBytes(&timeIn, range: NSRange(location: 4,length: 2))
timeData = CFSwapInt16BigToHost(timeIn.unsignedShortValue)
//24068
var heelIn: NSNumber = NSNumber(unsignedShort: 0)
newdata.getBytes(&heelIn, range: NSRange(location: 2, length: 2))
heelData = CFSwapInt16BigToHost(heelIn.unsignedShortValue)
//325
var frontIn: NSNumber = NSNumber(unsignedShort: 0)
newdata.getBytes(&frontIn, range: NSRange(location: 0, length: 2))
frontData = CFSwapInt16BigToHost(frontIn.unsignedShortValue)
//294
答案 0 :(得分:4)
NSNumber
是一个Foundation类,特别是值类型,
并且timeIn
是一个数字实例的指针。
您正在将字节提取到该指针中,这不是您想要的
并且可能导致各种未定义的行为或崩溃。
您应该将字节提取到UInt16
变量中:
var timeData:UInt16 = 0
newdata.getBytes(&timeData, range: NSRange(location: 4, length: 2))
timeData = CFSwapInt16BigToHost(timeData)
// Result: 1118 = 0x045E
上次转换的替代方法是
/// Creates an integer from its big-endian representation, changing the
/// byte order if necessary.
timeData = UInt16(bigEndian: timeData)