2013-10-08 28 views
0

This只有問題反之亦然。現在我得到這樣的:如何從UInt32數組轉換爲字節數組?

UInt32[] target; 

byte[] decoded = new byte[target.Length * 2]; 
Buffer.BlockCopy(target, 0, decoded, 0, target.Length); 

這是不行的,我得到陣列充滿0x00

+0

這將是錯誤的,即使它已經奏效。 'decode'只是它應該的大小的一半(一個'uint'是4個字節,因此該因子必須是4)。而'BlockCopy'的最後一個參數是'byte'計數,而不是'uint'-count。 – harold

+0

一種方法可以是使用顯式佈局定義結構。 以下內容可能會對您有所幫助: http://social.msdn.microsoft.com/Forums/zh-CN/60150e7b-665a-49a2-8e2e-2097986142f3/c-equivalent-to-c-union?forum=csharplanguage –

+0

哪種排序? 'BlockCopy'使用本地排序,這在我的經驗中很少是所需的行爲。 – CodesInChaos

回答

3

我建議像下面這樣:

UInt32[] target; 

//Assignments 

byte[] decoded = new byte[target.Length * sizeof(uint)]; 
Buffer.BlockCopy(target, 0, decoded, 0, decoded.Length); 

見代碼:

uint[] target = new uint[] { 1, 2, 3 }; 

//Assignments 

byte[] decoded = new byte[target.Length * sizeof(uint)]; 
Buffer.BlockCopy(target, 0, decoded, 0, decoded.Length); 

for (int i = 0; i < decoded.Length; i++) 
{ 
    Console.WriteLine(decoded[i]); 
} 

Console.ReadKey(); 

另見:

3

可以使用BitConverter.GetBytes方法用於將unitbyte

+0

唯一的'BitConverter.GetBytes()'是,如果你有一個'UInt32s'大數組,並且你需要把整個東西轉換成一個'Bytes'數組......然後你最終分配很多的byte [4] s',並且必須將它們添加到您的結果數組中......它實際上可能最終會有點慢。 – Andrew

1

你需要多個由4來創建byte陣列,由於UInt32是4個字節(32位)。但是,使用BitConverter並填寫byte的列表,如果需要,您可以稍後創建一個陣列。

UInt32[] target = new UInt32[] { 1, 2, 3 }; 
byte[] decoded = new byte[target.Length * 4]; //not required now 
List<byte> listOfBytes = new List<byte>(); 
foreach (var item in target) 
{ 
    listOfBytes.AddRange(BitConverter.GetBytes(item)); 
} 

如果你需要數組,那麼:

byte[] decoded = listOfBytes.ToArray(); 
1

你的代碼中有幾個錯誤:

UInt32[] target = new uint[] { 1, 2, 3, 4 }; 

// Error 1: 
// You had 2 instead of 4. Each UInt32 is actually 4 bytes. 
byte[] decoded = new byte[target.Length * 4]; 

// Error 2: 
Buffer.BlockCopy(
    src: target, 
    srcOffset: 0, 
    dst: decoded, 
    dstOffset: 0, 
    count: decoded.Length // You had target.Length. You want the length in bytes. 
); 

這應該得到你期待什麼。

2

試試這個代碼。這個對我有用。

UInt32[] target = new UInt32[]{1,2,3}; 
    byte[] decoded = new byte[target.Length * sizeof(UInt32)]; 
    Buffer.BlockCopy(target, 0, decoded, 0, target.Length*sizeof(UInt32)); 

    foreach(byte b in decoded)  
    { 
     Console.WriteLine(b); 
    } 
相關問題