我如何将24位整数转换为3字节数组?

问题描述 投票:2回答:3

嘿,我完全不在我的深度之内,我的大脑开始受伤。.:(

我需要隐藏一个整数,以使其适合于3个字节的数组。(是否是24bit的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,这是我发送数据也需要做的转换。

任何帮助,不胜感激!

objective-c bytearray nsdata bytestring tcpsocket
3个回答
1
投票

您可以使用联合:

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)上运行。


6
投票

假设您有一个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];

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


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

[如果要在生产代码中使用它,可能会需要注意的事情,但是基本思想是理智的。

© www.soinside.com 2019 - 2024. All rights reserved.