
string 类型转成 byte[]
1
|
byte[] byteArray = System.Text.Encoding.Default.GetBytes(str);
|
byte[] 转成 string
1
|
string str = System.Text.Encoding.Default.GetString(byteArray);
|
string 类型转成 ASCII byte[]
(“01” 转成 byte[] = new byte[]{0x30,0x31})
1
|
byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(str);
|
ASCIIbyte[] 转成 string
** (byte[] = new byte[]{0x30,0x31} 转成 “01”)
1
|
string str = System.Text.Encoding.ASCII.GetString(byteArray);
|
byte[] 转16进制格式 string
new byte[]{0x30,0x31} 转成 “3031”
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
public static string (byte[] bytes) { string hexString = string.Empty; if(bytes != null) { StringBuilder strB = new StringBuilder(); for(int i = 0; i < bytes.Length; i++) { strB.Append(bytes[i].ToString("x2")); } hexString = strB.ToString(); } return hexString; }
|
16进制格式 string 转 byte[]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
public static byte[] GetBytes(string hexString, out int discarded) { discarded = 0; string newString = ""; char c; for(int i = 0; i < hexString.Length; i++) { c = hexString[i]; if(IsHexDig(c)) new String += c; else discarded++; } if(newString.Length % 2 != 0) { discarded++; newString = newString.Substring(0, newString.Length - 1); } int byteLength = newString.Length / 2; byte[] bytes = new byte[byteLength]; string hex; int j = 0; for(int i = 0; i < bytes.Length; i++) { hex = new String(new Char[]{newString[j], newString[j + 1]}); bytes[i] = HexToByte(hex); j = j + 2; } return bytes; }
|
近期评论