在objective-c中将二进制二进制补码数据转换为整数 [英] Convert binary two's complement data into integer in objective-c
问题描述
我有一些来自加速度计的二进制数据(二进制补码),我需要将其转换为整数.是否有一个标准库函数可以做到这一点,还是我需要编写自己的代码?
I have some binary data (twos complement) coming from an accelerometer and I need to convert it to an integer. Is there a standard library function which does this, or do I need to write my own code?
例如:我从加速度计接收到一个 NSData 对象,当转换为十六进制时,它看起来像这样:
For example: I receive an NSData object from the acclerometer, which when converted to hex looks like this:
C0088001803F
这是 3 个 2 字节数据块的串联:
Which is a concatenation of 3 blocks of 2-byte data:
x = C008
y = 8001
z = 803F
只关注 x 轴:
hex = C008
decimal = 49160
binary = 1100000000001000
twos complement = -16376
有没有标准函数可以将二进制补码的 C008 直接转换为 -16376?
Is there a standard function for converting from C008 in twos complement directly to -16376?
谢谢.
推荐答案
类似:
const int8_t* bytes = (const int8_t*) [nsDataObject bytes];
int32_t x = (bytes[0] << 8) + (0x0FF & bytes[1]);
x = x << 16;
x = x >> 16;
int32_t y = (bytes[2] << 8) + (0x0FF & bytes[3]);
y = y << 16;
y = y >> 16;
int32_t z = (bytes[4] << 8) + (0x0FF & bytes[5]);
z = z << 16;
z = z >> 16;
这假设值确实是问题中建议的大端".
This assumes that the values really are "big-endian" as suggested in the question.
这篇关于在objective-c中将二进制二进制补码数据转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!