2010-12-07 157 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

相關問題