2010-05-13 41 views
2

我有10個字節 - 4個字節的低階,4個字節的高階,2個字節的最高階 - 我需要轉換爲無符號長。我已經嘗試了幾種不同的方法,但都沒有工作:如何轉換10個字節爲無符號長

嘗試#1:

var id = BitConverter.ToUInt64(buffer, 0); 

嘗試#2:

var id = GetID(buffer, 0); 

long GetID(byte[] buffer, int startIndex) 
     { 
      var lowOrderUnitId = BitConverter.ToUInt32(buffer, startIndex); 
      var highOrderUnitId = BitConverter.ToUInt32(buffer, startIndex + 4); 
      var highestOrderUnitId = BitConverter.ToUInt16(buffer, startIndex + 8); 
      return lowOrderUnitId + (highOrderUnitId * 100000000) + (highestOrderUnitId * 10000000000000000); 
     } 

任何幫助,將不勝感激,謝謝!

+1

你從哪裏得到一個10字節長? 10個字節是80位,不適合64位長。 – 2010-05-13 23:50:40

+0

我最後一次檢查無符號長整型是64位寬。你期望得到什麼?這些術語是你乘以最後一行應該是十六進制的嗎? – 2010-05-13 23:51:00

+0

不長只有8個字節? – tbischel 2010-05-13 23:53:10

回答

2

如註釋所示,10個字節不適合long(這是一個64位數據類型 - 8字節)。但是,你可以使用一個decimal(這是128位寬 - 16個字節):

var lowOrderUnitId = BitConverter.ToUInt32(buffer, startIndex); 
var highOrderUnitId = BitConverter.ToUInt32(buffer, startIndex + 4); 
var highestOrderUnitId = BitConverter.ToUInt16(buffer, startIndex + 8); 

decimal n = highestOrderUnitId; 
n *= UInt32.MaxValue; 
n += highOrderUnitId; 
n *= UInt32.MaxValue; 
n += lowOrderUnitId; 

我沒有實際測試過這一點,但我認爲它會工作...

+0

我認爲你需要用'1m + UInt32.MaxValue'(兩個地方)替換'UInt32.MaxValue'。 – 2013-02-23 18:13:34

0

由於一直上面提到的一個ulong不足以容納10個字節的數據,它只有8個字節。您需要使用Decimal。最有效的方法(更不用提最少的代碼),很可能會得到一個UInt64了它,再加入高序位:

ushort high = BitConverter.ToUInt16(buffer, 0); 
ulong low = BitConverter.ToUInt64(buffer, 2); 
decimal num = (decimal)high * ulong.MaxValue + high + low; 

(您需要添加high第二次,否則你需要乘以值ulong.MaxValue + 1,這是很多令人討厭的鑄造和括號。)

+0

也許可以用'decimal'類型的'1m'來完成。然後你的最後一行會顯示:'decimal num = high *(ulong.MaxValue + 1m)+ low;' – 2013-02-23 18:15:30

相關問題