簡體   English   中英

將字節數組轉換為 int

[英]Convert byte array to int

我正在嘗試在 C# 中進行一些轉換,但我不知道該怎么做:

private int byteArray2Int(byte[] bytes)
{
    // bytes = new byte[] {0x01, 0x03, 0x04};

    // how to convert this byte array to an int?

    return BitConverter.ToInt32(bytes, 0); // is this correct? 
    // because if I have a bytes = new byte [] {0x32} => I got an exception
}

private string byteArray2String(byte[] bytes)
{
   return System.Text.ASCIIEncoding.ASCII.GetString(bytes);

   // but then I got a problem that if a byte is 0x00, it show 0x20
}

誰能給我一些想法?

BitConverter是正確的方法。

您的問題是因為您在承諾 32 時只提供了 8 位。請嘗試在數組中使用有效的 32 位數字,例如new byte[] { 0x32, 0, 0, 0 }

如果要轉換任意長度的數組,可以自己實現:

ulong ConvertLittleEndian(byte[] array)
{
    int pos = 0;
    ulong result = 0;
    foreach (byte by in array) {
        result |= ((ulong)by) << pos;
        pos += 8;
    }
    return result;
}

目前尚不清楚您的問題的第二部分(涉及字符串)應該產生什么,但我想您想要十六進制數字? 前面的問題所述, BitConverter也可以提供幫助。

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first), 
// reverse the byte array. 
if (BitConverter.IsLittleEndian)
  Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
  1. 這是正確的,但是您缺少Convert.ToInt32 '想要' 32 位(32/8 = 4字節)的信息來進行轉換,因此您不能只轉換一個字節:`new byte [] {0x32}

  2. 絕對和你一樣的麻煩。 並且不要忘記您使用的編碼:從編碼到編碼,您有“每個符號的不同字節數”

一種快速簡單的方法是使用 Buffer.BlockCopy 將字節復制到 integer:

UInt32[] pos = new UInt32[1];
byte[] stack = ...
Buffer.BlockCopy(stack, 0, pos, 0, 4);

這具有額外的好處,即能夠僅通過操作偏移量將大量整數解析為數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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