2013-02-21 71 views
6

我已經在我的代碼的byte [] srno轉換整個字節[]到UINT

byte[] srno = new byte[6]; 

srno[0] = 0xff; 
srno[1] = 0x0f; 
srno[2] = 0x24; 
srno[3] = 0x12; 
srno[4] = 0x16; 
srno[5] = 0x0a; 

現在我要像

uint a = 0xff0f2412160a; 

如何轉換在UINT這個價值?

+3

一個'uint'爲4個字節,但你6字節在那裏。無論如何,你知道'BitConverter'類嗎? – Ani 2013-02-21 12:19:40

+0

只要做數學運算:'srno [0] * 0x10000000000 + srn0 [1] * 0x100000000 ...'。管他呢。 – 2013-02-21 12:19:55

+0

@Ani:好的沒問題告訴我ulong? BitConverter類需要索引我不想爲特定索引我想轉換整個數組 – Kevan 2013-02-21 12:21:04

回答

8

正如@animaonline建議的那樣,您應該使用BitConverter將字節數組轉換爲uint或* ulong。因此你有6個字節,uint對你來說太小了。你應該轉換爲ulong *。但轉換器需要八個字節,因此與所需的字節數創建新的數組:

byte[] value = new byte[8]; 
Array.Reverse(srno); // otherwise you will have a1612240fff result 
Array.Copy(srno, value, 6); 
ulong result = BitConverter.ToUInt64(value, 0); 
Console.WriteLine("{0:x}", result); // ff0f2412160a 
+1

這工作正如我所願! – Kevan 2013-02-21 12:40:17

0

在System命名空間中,你會發現BitConverter庫類。你想靜態ToUInt64()功能如下:

var a = BitConvert.ToUInt64(srno, 0); 

您需要將您的數組的大小調整到[8]

MSDN

+1

你需要先倒置數組! – 2013-02-21 12:34:16

0

大家似乎忽略了他所期望的字節順序編碼輸出。 BitConverter類使用固定編碼(通常是Little-Endian,IIRC)。示例中的輸出假定爲Big-Endian。在一個完美的世界中,你只需要自己做數學,但使用Array.Reverse然後使用內置的BitConverter類更簡單。

有可能將是答案一堆之前,我張貼此所以這裏是一個非常快的一段不安全代碼:

public static unsafe ulong ToULong(byte[] values) 
{ 
    byte* buffer = stackalloc byte[8]; 
    if (BitConverter.IsLittleEndian) 
     Array.Reverse(values); 
    System.Runtime.InteropServices.Marshal.Copy(values, 0, (IntPtr)buffer, values.Length); 
    return *(ulong*)buffer; 
}