转换二进制补码数据转换成整数,在Objective-C [英] Convert binary two's complement data into integer in objective-c

查看:302
本文介绍了转换二进制补码数据转换成整数,在Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些二进制数据(二进制补码)的加速度计快到了,我需要将其转换为整数。是否有一个标准库函数做到这一点,或者我需要写我自己的code?

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对象从acclerometer,将其转换为十六进制是这样的:

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

C0088001803F

这是一个2字节数据的3个街区串联:

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

x = C008
y = 8001
z = 803F

集中于仅在x轴:

Focussing on the x-axis only:

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屋!

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