如何将 24 位整数转换为 3 字节数组?
嘿,我完全超出了我的能力范围,我的大脑开始受伤了..:(
我需要隐藏一个整数,以便它适合 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 ,这是我需要做的转换回来以发送 任何帮助
非常感谢!
Hey Im totally out of my depth and my brain is starting to hurt.. :(
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
I have:
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
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您有一个 32 位整数。您希望将底部 24 位放入字节数组中:
将 3 个字节转换回整数:
而且,是的,我完全意识到有更优化的方法可以做到这一点。上述目标是清晰的。
Assume you have a 32-bit integer. You want the bottom 24 bits put into a byte array:
To convert the 3 bytes back to an integer:
And, yes, I'm fully aware that there are more optimal ways of doing it. The goal in the above is clarity.
您可以使用 union:
从 int 转换为 bytes:
从 bytes 转换为 int:
注意:以这种方式使用 union 依赖于处理器字节顺序。我给出的示例适用于小端系统(如 x86)。
You could use a union:
to convert from int to bytes:
to convert from bytes to int:
Note: using unions in this manner relies on processor byte-order. The example I gave will work on a little-endian system (like x86).
来点指针技巧怎么样?
如果您打算在生产代码中使用它,可能需要注意一些事情,但基本思想是合理的。
How about a bit of pointer trickery?
There are probably things to be taken care of, if you are going to use this in production code, but the basic idea is sane.