将 NSData 转换为有符号整数 [英] Convert NSData to signed integer

查看:74
本文介绍了将 NSData 转换为有符号整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了一些类似的问题,但我无法回答:

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

我在 NSData 对象中收到一个 16 位有符号整数,例如0xFF3C".我怎样才能从中读出正确的数字?

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

根据詹姆斯韦伯斯特的回答,我得到:

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

这显然是不正确的(我预计 +/- 2000)

which clearly is not correct (I expect +/- 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>

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

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

推荐答案

其实挺难的问题!

这是我尝试的第 20 件事,似乎工作正常:

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

输出为:

65340

这篇关于将 NSData 转换为有符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆