Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top