2010-12-07 162 views
2

嘿我完全没有我的深度和我的大脑开始伤害.. :(如何将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正确,这是我需要做的以及发送数据的转换。

任何帮助非常感谢!

回答

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)上工作。

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 

如果你打算在生产代码中使用它,但基本想法是理智的,可能有些事情需要注意。

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

+1它是endian不可知的,这是很好的。 – JeremyP 2010-12-07 15:39:27

+0

只要数字<255我工作的很好,我收集这是一个24位整数的最大值? – loststudent 2010-12-08 10:02:48

相关问题