天天看點

C# 位元組數組、字元串轉化位元組數組轉字元串字元串轉位元組數組位元組數組轉整數整數轉位元組數組字元串轉位元組字元串轉數值數值轉字元串

最近經常使用數值、字元串與位元組數組的互相轉化,對所用方法進行簡單整理

語言:C#

位元組數組轉字元串

string str = BitConverter.ToString(bytes);
// In: { 0x1A, 0x2B, 0x3C} 
// Out: "1A-2B-3C"

string str = Encoding.UTF8.GetString(bytes);
// In: { 0x30, 0x31, 0x32} 
// Out: "012"
           

字元串轉位元組數組

byte[] bytes = Encoding.UTF8.GetBytes(str);
// In: "123"
// Out: { 0x31, 0x32, 0x33 }
           

位元組數組轉整數

int i = BitConverter.ToInt32(bytes, 0);
// In: { 0x01, 0x02, 0x03, 0x04 }
// Out: 0x04030201 (67305985)
           

整數轉位元組數組

byte[] bytes = BitConverter.GetBytes(Int16);
// In: 16
// Out: {0x00, 0x10}
           

字元串轉位元組

byte b = Convert.ToByte(str, 16)
// In: "12"
// Out: 0x12
           

字元串轉數值

double d = Convert.ToDouble(str);
// In: "12.5"
// Out: 12.5

int i = Convert.ToInt32(str);
// In: "1234"
// Out: 1234
           

數值轉字元串

int i = 12;
double d = 35.7;
string str = i.ToString();
str = d.ToString();