最近经常使用数值、字符串与字节数组的相互转化,对所用方法进行简单整理
语言: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();