[英]What is the easiest way to read different length bit fields in a byte array?
[英]What's the easiest way to add a zero-byte to a byte array?
嘗試這個:
byte[] bytes = ...
if ((bytes[bytes.Length - 1] & 0x80) != 0)
{
Array.Resize<byte>(ref bytes, bytes.Length + 1);
}
BigInteger result = new BigInteger(bytes);
使用靜態方法System.Array.Resize。 在你的情況下:
byte[] b = Guid.NewGuid().ToByteArray();
System.Array.Resize<byte>(ref b, b.Length + 1);
b[b.Length - 1] = 0;
var dest = new byte[17];
Array.Copy(Guid.NewGuid().ToByteArray(), dest , 16);
BigInteger bi = new BigInteger(dest);
我認為它在頁面底部進行了解釋。 請看一下樣品:
ulong originalNumber = UInt64.MaxValue;
byte[] bytes = BitConverter.GetBytes(originalNumber);
if (originalNumber > 0 && (bytes[bytes.Length - 1] & 0x80) > 0)
{
byte[] temp = new byte[bytes.Length];
Array.Copy(bytes, temp, bytes.Length);
bytes = new byte[temp.Length + 1];
Array.Copy(temp, bytes, temp.Length);
}
BigInteger newNumber = new BigInteger(bytes);
Console.WriteLine("Converted the UInt64 value {0:N0} to {1:N0}.",
originalNumber, newNumber);
請注意,此代碼是從MSDN站點復制的,以顯示如何處理在轉換為BigInt期間可能被視為負數的大數字。 在效率方面,這不是你能得到的最好的,並且在這個帖子中提供了更好的片段。
這看起來很簡單:
var bytesAfter = bytesBefore.Concat(new byte[] { 0 }).ToArray();
單程:
var x = BigInteger.Abs(new BigInteger(bytes));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.