1

我已经看到了一些类似的问题,但我无法做到这一点:

我在 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>

这看起来真的很有趣/烦人。这可能是什么来的?

4

3 回答 3

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

于 2012-08-07T08:08:11.757 回答
1

我找到了一种简单的方法来做到这一点,检查它是否适合你。

我这样做了:

int value;
[characteristic.value getBytes:&value length:2];

只需将长度更改为您需要的长度。

于 2014-05-09T17:48:52.597 回答
0

我自己从来没有这样做过。但是,假设您的 2 字节数据在 myData 中,这应该可以工作:

unsined short myInt = (int) [myData bytes];

您可能想测试 myData.lenght 是否真的等于 2。

于 2012-08-07T08:12:31.893 回答