我已经看到了一些类似的问题,但我无法做到这一点:
我在NSData对象中收到一个16位有符号整数,例如'0xFF3C'。如何从中读出正确的数字?
编辑:詹姆斯韦伯斯特的答案我得到了:Received hex value : <0800>
Converted value: 803995656
Received hex value : <0a00>
Converted value: 803995658
Received hex value : <1a00>
Converted value: 803995674
Received hex value : <faff>
Converted value: 804061178
Received hex value : <e4ff>
Converted value: 804061156
Received hex value : <f0ff>
Converted value: 804061168
显然不正确(我希望+/- 2000)
编辑:一些代码:
-(void)characteristicValueRead:(CBCharacteristic *)characteristic{
unsigned short myInt = (int) [characteristic.value bytes];
NSLog(@"Received value: %@", characteristic.value);
NSLog(@"Converted value: %i",(int)myInt);
}
通过这个片段,我得到了:
Received value: <0000>
Converted value: 26176
Received value: <0000>
Converted value: 46688
Received value: <0000>
Converted value: 30576
Received value: <0000>
Converted value: 2656
Received value: <0000>
Converted value: 50896
Received value: <0000>
看起来非常有趣/烦人。这会是什么来的?
答案 0 :(得分:1)
实际上是一个非常困难的问题!
这是我尝试的第20件事,似乎工作正常:
NSData *data = [NSData dataWithBytes:"FF3C" length:4];
NSString *string = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
string = [@"0x" stringByAppendingString:string];
unsigned short value;
sscanf([string UTF8String], "%hx", &value);
NSLog(@"%d", value);
,输出为:
65340
答案 1 :(得分:1)
我找到了一种简单的方法,检查它是否适合你。
我这样做了:
int value;
[characteristic.value getBytes:&value length:2];
只需将长度更改为您需要的长度。
答案 2 :(得分:0)
我自己从未这样做过。但是,假设您的2字节数据位于myData中,这应该可以正常工作:
unsined short myInt = (int) [myData bytes];
你可能想测试myData.lenght真的等于2.