byte[] 數組和字符串的轉換,與byte[] 數組和int類型的之間的轉化


我們先來看看byte bool  int ushort  等的定義

 

首先時byte[]數組與string之間的轉換

string 轉換位byte[] 數組

string str = "1-1";
byte[] cmd = Encoding.Default.GetBytes(str);
View Code

byte[] 數組轉化位string

string str = "1-1";
 byte[] cmd = Encoding.Default.GetBytes(str);
 string str1 = Encoding.Default.GetString(cmd);

將int型轉化為byte[]數組

int i = 255;
byte[] intBuff = BitConverter.GetBytes(i);  

將byte[]數組轉化為int

int i = 255;
byte[] intBuff = BitConverter.GetBytes(i);     // 將 int 轉換成字節數組
 i = BitConverter.ToInt32(intBuff, 0);           // 從字節數組轉換成 int

 2 字節序(大端字節序和小段字節序)很大程度參考了https://www.cnblogs.com/lxjshuju/p/7119370.html

網絡字節序就是大端順序,由於TCP/IP首部中全部的二進制整數在網絡中傳輸時都要求以這樣的次序,因此它又稱作網絡字節序。

主機字節順序就是指相對於網絡傳輸是的字節順序的主機上的字節順序。有大端表示法,小端表示法

本文中byte[]的順序依照“大端順序”。這句話的意思是說對於整數0x11223344

byte[0]保存0x11。byte[1]保存0x22。byte[2]保存0x33,byte[3]保存0x44

char 轉化為byte[2]數組

public static byte[] CharToBytes(char c)
        {
            byte[] cmd = new byte[2];
            cmd[0] = (byte)((c & 0xff00) >> 8);
            cmd[1] = (byte)(c & 0x00ff);
            return cmd;
        }

 

 //byte[] 數組轉化為char

 public static char getChar(byte[] arr, int index)
        {
            return (char)(0xff00 & arr[index] << 8 | (0xff & arr[index + 1]));
        }

 同理short ushort int 

long轉化為byte[] 數組

 

 public static byte[] getByteArray(long L)
        {
            byte[] b = new byte[8];
            b[0] = (byte)(0xff & (L >> 56));
            b[1] = (byte)(0xff & (L >> 48));
            b[2] = (byte)(0xff & (L >> 40));
            b[3] = (byte)(0xff & (L >> 32));
            b[4] = (byte)(0xff & (L >> 24));
            b[5] = (byte)(0xff & (L >> 16));
            b[6] = (byte)(0xff & (L >> 8));
            b[7] = (byte)(0xff & L);
            return b;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM