Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

ios - 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?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...