Convert NSData to signed integer

守給你的承諾、 提交于 2019-12-11 05:41:57

问题


I have seen some similiar questions but I can't get this right:

I receive a 16 bit signed integer in an NSData object, e.g '0xFF3C'. How can I read out the correct number from this?

EDIT: With James Webster's answer I get:

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

which clearly is not correct (I expect +/- 2000)

EDIT: Some code:

-(void)characteristicValueRead:(CBCharacteristic *)characteristic{

  unsigned short myInt = (int) [characteristic.value bytes];
  NSLog(@"Received value: %@", characteristic.value);
  NSLog(@"Converted value: %i",(int)myInt);
}

With this snippet I get:

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>

which looks really interesting/annoying. What could this come from?


回答1:


Actually quite a difficult problem!

This was about the 20th thing I tried, and seems to work ok:

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);

and the output is:

65340




回答2:


I found an easy way to do that, check if it work for you.

I did this:

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

And just change the length to what you need.




回答3:


I never did that myself. However, this should work assuming your 2 byte data is in myData:

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

You may want to test wether myData.lenght really equals 2.



来源:https://stackoverflow.com/questions/11841564/convert-nsdata-to-signed-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!