コードに byte[] srno があります
byte[] srno = new byte[6];
srno[0] = 0xff;
srno[1] = 0x0f;
srno[2] = 0x24;
srno[3] = 0x12;
srno[4] = 0x16;
srno[5] = 0x0a;
今、私はこの値を uint のようにしたい
uint a = 0xff0f2412160a;
どのように変換するのですか?
@animaonline が提案したようBitConverter
に、バイト配列をuintまたは *ulong に変換するために使用する必要があります。したがって、6バイトがあり、uintは小さすぎます。ulong* に変換する必要があります。ただし、コンバーターには 8 バイトが必要なので、必要なバイト数で新しい配列を作成します。
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
In System namespace you will find the BitConverter
library class. You want the static ToUInt64()
function as follows:
var a = BitConvert.ToUInt64(srno, 0);
You will need to adjust the size of your array to [8]
期待される出力のバイト順エンコーディングを誰もが無視しているようです。このBitConverter
クラスは、固定エンコーディング (通常はリトル エンディアン、IIRC) を使用します。この例の出力は、ビッグ エンディアンであると想定されています。完璧な世界では、自分で計算するだけですが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;
}