字串和Byte轉換(byte to string, string to byte)
系統預設編碼格式:
string str = "Ruyut";
byte[] bytes = Encoding.Default.GetBytes(str);
string s = Encoding.Default.GetString(bytes);
UTF8:
string str = "Ruyut";
byte[] bytes = Encoding.UTF8.GetBytes(str);
string s = Encoding.UTF8.GetString(bytes);
ASCII:
string str = "Ruyut";
byte[] bytes = Encoding.ASCII.GetBytes(str);
string s = Encoding.ASCII.GetString(bytes);
字串和Base64轉換(base64 to string, string to base64)
// 字串轉Base64
string str = "Ruyut";
byte[] bytes = Encoding.UTF8.GetBytes(str);
string base64String = Convert.ToBase64String(bytes);
Console.WriteLine(base64String); // UnV5dXQ=
// Base64轉字串
byte[] base64Bytes = Convert.FromBase64String(base64String);
string s = Encoding.UTF8.GetString(base64Bytes);
Console.WriteLine(s); // Ruyut
字串和 hex(十六進位字串)轉換(hex to string, string to hex)
// 字串轉 hex(十六進位字串)
string str = "Ruyut";
string hexString = Convert.ToHexString(Encoding.Default.GetBytes(str));
Console.WriteLine(hexString); // 5275797574
// hex轉字串
string s = Encoding.UTF8.GetString(Convert.FromHexString(hexString));
Console.WriteLine(s); // Ruyut
包含'-'分割的hex字串:
// 字串轉 hex(十六進位字串) 使用 '-'分割
string str = "Ruyut";
byte[] bytes = Encoding.UTF8.GetBytes(str);
string base64String = BitConverter.ToString(bytes);
Console.WriteLine(base64String); // 52-75-79-75-74
// hex轉字串
String[] strings = base64String.Split('-');
byte[] array = new byte[strings.Length];
for (int i = 0; i < strings.Length; i++) array[i] = Convert.ToByte(strings[i], 16);
string s = Encoding.UTF8.GetString(array);
Console.WriteLine(s); // Ruyut
hex轉字串的參考連結
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com