Convert binary two's complement data into integer in objective-c

杀马特。学长 韩版系。学妹 提交于 2019-11-30 06:01:07

问题


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?

For example: I receive an NSData object from the acclerometer, which when converted to hex looks like this:

C0088001803F

Which is a concatenation of 3 blocks of 2-byte data:

x = C008
y = 8001
z = 803F

Focussing on the x-axis only:

hex = C008
decimal = 49160
binary = 1100000000001000
twos complement = -16376

Is there a standard function for converting from C008 in twos complement directly to -16376?

Thank you.


回答1:


Something like:

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.



来源:https://stackoverflow.com/questions/21931789/convert-binary-twos-complement-data-into-integer-in-objective-c

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