簡體   English   中英

向字節數組添加零字節最簡單的方法是什么?

[英]What's the easiest way to add a zero-byte to a byte array?

我正在將byte[]轉換為BigInteger ,我想確保它是正面的。 文檔說

要防止將正值誤解為負值,可以在數組末尾添加零字節值。

但它沒有具體說明。 那么,我該怎么做呢?


發現這是最簡單的:

public static BigInteger UnsignedBigInt(byte[] bytes)
{
    if ((bytes[bytes.Length - 1] & 0x80) != 0) Array.Resize(ref bytes, bytes.Length + 1);
    return new BigInteger(bytes);
}

謝謝dtb

嘗試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM