los*_*ent 2 bytearray objective-c nsdata bytestring tcpsocket
嘿我完全超出了我的深度,我的大脑开始受伤... :(
我需要转换一个整数,以便它适合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
Run Code Online (Sandbox Code Playgroud)
我想我的主要问题是我不知道如何检查我确实正确地转换了我的int,这也是我需要做的转换以及发送数据.
任何帮助非常感谢!
假设您有一个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;
Run Code Online (Sandbox Code Playgroud)
要将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];
Run Code Online (Sandbox Code Playgroud)
而且,是的,我完全清楚有更多的最佳方式.上面的目标是清晰度.
| 归档时间: |
|
| 查看次数: |
4242 次 |
| 最近记录: |