嘿,我完全摆脱了我的深度,我的大脑开始受到伤害.. :(

我需要掩盖一个整数,以使其适合3个字节数组。(是24位int?)然后返回以通过插座从字节流发送/接收此号码

我有:

NSMutableData* data = [NSMutableData data];

 int msg = 125;

 const void *bytes[3];

 bytes[0] = msg;
 bytes[1] = msg >> 8;
 bytes[2] = msg >> 16;

 [data appendBytes:bytes length:3];

 NSLog(@"rtn: %d", [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] intValue]);

 //log brings back 0

我想我的主要问题是我不知道如何检查我确实正确地转换了我的int,这是我需要做的转换,以及发送数据。

任何帮助都非常感谢!

有帮助吗?

解决方案

您可以使用工会:

union convert {
    int i;
    unsigned char c[3];
};

从int转换为字节:

union convert cvt;
cvt.i = ...
// now you can use cvt.c[0], cvt.c[1] & cvt.c[2]

从字节转换为int:

union convert cvt;
cvt.i = 0; // to clear the high byte
cvt.c[0] = ...
cvt.c[1] = ...
cvt.c[2] = ...
// now you can use cvt.i

注意:以这种方式使用工会依赖于处理器字节订单。我给出的示例将在小型系统(例如x86)上使用。

其他提示

假设您有一个32位整数。您希望将底部的24位放入一个字节阵列中:

int msg = 125;
byte* bytes = // allocated some way

// Shift each byte into the low-order position and mask it off
bytes[0] = msg & 0xff;
bytes[1] = (msg >> 8) & 0xff;
bytes[2] = (msg >> 16) & 0xff;

将3个字节转换回整数:

// Shift each byte to its proper position and OR it into the integer.
int msg = ((int)bytes[2]) << 16;
msg |= ((int)bytes[1]) << 8;
msg |= bytes[0];

而且,是的,我完全意识到有更多最佳方法可以做到这一点。上述目标是清晰。

一些指针骗局怎么样?

int foo = 1 + 2*256 + 3*65536;
const char *bytes = (const char*) &foo;
printf("%i %i %i\n", bytes[0], bytes[1], bytes[2]); // 1 2 3

如果您要在生产代码中使用它,那么可能需要处理一些事情,但是基本思想是理智的。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top