位元組數組與int轉換

來源:互聯網
上載者:User

     在C#中將INT型轉為位元組數組後,其是以高位到低位排序儲存的,而在C++和JAVA中是以低位到高位排序的,以致如果直接將轉換後的位元組數組與C++或JAVA通訊時會出錯。需要反排序後再傳輸。

   

    位元組轉為Int代碼

    C#轉碼如下:

   

C#
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)   //判斷電腦結構的 endian 設定    Array.Reverse(bytes);    //轉換排序int i = BitConverter.ToInt32(bytes, 0);Console.WriteLine("int: {0}", i);// Output: int: 25
BitConverter.IsLittleEndian 欄位為指示資料在此電腦結構中儲存時的位元組順序(“Endian”性質)。

如果結構為 Little-endian,則該值為 true;如果結構為 Big-endian,則該值為 false

不同的電腦結構採用不同的位元組順序儲存資料。“Big-endian”表示最大的有效位元組位於單詞的左端。“Little-endian”表示最大的有效位元組位於單詞的右端。

 Int轉為位元組代碼

  C#轉碼如下:

  byte[] aa = BitConverter.GetBytes(1243);
  if (BitConverter.IsLittleEndian)
      Array.Reverse(aa);

 

 JAVA轉碼如下:

public byte[] int2bytes(int a, boolean isHighFirst)
        {
            byte[] result = new byte[4];

            if (isHighFirst)
            {
                result[0] = (byte)(a >> 24 & 0xff);
                result[1] = (byte)(a >> 16 & 0xff);
                result[2] = (byte)(a >> 8 & 0xff);
                result[3] = (byte)(a & 0xff);
            }
            else
            {
                result[3] = (byte)(a >> 24 & 0xff);
                result[2] = (byte)(a >> 16 & 0xff);
                result[1] = (byte)(a >> 8 & 0xff);
                result[0] = (byte)(a & 0xff);
            }
            return result;
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.