2013-01-22 59 views
6

的考慮到這些整數字節數組:創建整數集

public uint ServerSequenceNumber; 
public uint Reserved1; 
public uint Reserved2; 
public byte Reserved3; 
public byte TotalPlayers; 

什麼是創建一個從他們byte[]陣列的最佳方式?如果它們的全部值是1,那麼得到的陣列將是:

00000000000000000000000000000001 00000000000000000000000000000001 00000000000000000000000000000001 00000001 00000001 
+0

字節數組或位陣列?您可以使用http://msdn.microsoft.com/en-us/library/aa311381%28v=vs.71%29.aspx來獲取一個字節數組,然後您將不得不交換字節周圍的字節順序。 – Matthew

+0

你有什麼試過,爲什麼你需要一個字節數組,它是幹什麼用的?使它們成爲屬性,用屬性裝飾它們,然後將裝飾過的屬性寫入流中,然後將其作爲一個數組來抓取可能是最好的方法,當然可以作爲擴展或接口來重用。 –

+0

@Tony這是一個實時多人遊戲,它是從服務器發送給所有更新遊戲狀態的客戶端的消息。我設法從循環中獲得正確的數組,但我的方法太慢了。只是想知道最佳做法是什麼,因爲我對這種事情沒有太多經驗 –

回答

7

這應該做你想要的。 BitConverter按正在使用的處理器的字節順序返回一個字節數組。對於x86處理器來說,它是小端的。這首先放置最不重要的字節。

int value; 
byte[] byte = BitConverter.GetBytes(value); 
Array.Reverse(byte); 
byte[] result = byte; 

如果你不知道你將要使用的應用程序在處理器上,我建議使用:

int value; 
byte[] bytes = BitConverter.GetBytes(value); 
if (BitConverter.IsLittleEndian){ 
Array.Reverse(bytes); 
} 
byte[] result = bytes; 
+1

+1,但它不創建「向後」數組,「BitConverter」按正在使用的處理器的字節順序返回一個字節數組,這恰好是x86處理器上的小端(最低有效字節在前) 。 – Matthew

+0

非常真實我將編輯我如何說明答案 – Robert

+0

@羅伯特感謝偉大工程,我已經添加了我自己的答案基於你http://stackoverflow.com/a/14464592/356635 –

2

這個怎麼樣?

byte[] bytes = new byte[14]; 
int i = 0; 
foreach(uint num in new uint[]{SecureSequenceNumber, Reserved1, Reserved2}) 
{ 
    bytes[i] = (byte)(num >> 24); 
    bytes[i + 1] = (byte)(num >> 16); 
    bytes[i + 2] = (byte)(num >> 8); 
    bytes[i + 3] = (byte)num; 
    i += 4; 
} 
bytes[12] = Reserved3; 
bytes[13] = TotalPlayers; 
+0

謝謝,更新的問題!愚蠢的錯誤:) –

1

擴大對@羅伯特的回答我創建了一個簡單的類,使事情變得更整潔,當你做很多concatanations的:

class ByteJoiner 
{ 
    private int i; 
    public byte[] Bytes { get; private set; } 

    public ByteJoiner(int totalBytes) 
    { 
     i = 0; 
     Bytes = new byte[totalBytes]; 
    } 

    public void Add(byte input) 
    { 
     Add(BitConverter.GetBytes(input)); 
    } 
    public void Add(uint input) 
    { 
     Add(BitConverter.GetBytes(input)); 
    } 
    public void Add(ushort input) 
    { 
     Add(BitConverter.GetBytes(input)); 
    } 
    public void Add(byte[] input) 
    { 
     System.Buffer.BlockCopy(input, 0, Bytes, i, input.Length); 
     i += input.Length; 
    } 
}