如何将24位整数转换为3字节数组? [英] How do I convert a 24-bit integer into a 3-byte array?
问题描述
嘿,我完全超出了我的深度,我的大脑开始受伤..:(
Hey Im totally out of my depth and my brain is starting to hurt.. :(
我需要隐藏一个整数,以使其适合3字节数组(是24位整数吗?),然后再次返回以通过套接字从字节流中发送/接收此数字
I need to covert an integer so that it will fit in a 3 byte array.(is that a 24bit int?) and then back again to send/receive this number from a byte stream through a socket
我有:
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,这是我发送数据也需要做的转换.
I guess my main problem is that I do not know how to check that I have indeed converted my int correctly which is the converting back that I need to do as well for sending the data.
任何帮助都将不胜感激!
Any help greatly appreciated!
推荐答案
您可以使用联合:
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)上工作.
Note: using unions in this manner relies on processor byte-order. The example I gave will work on a little-endian system (like x86).
这篇关于如何将24位整数转换为3字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!