数据类型-string与byte、byte[]的转换

string str1 = "Im a killer";
char[] chars = str1.ToCharArray();
byte[] bytes = new byte[chars.Length];
for (int i = 0; i<chars.Length;i++)
{
          
   
	Debug.Log(chars[i]);
	bytes[i] = Convert.ToByte(chars[i]);
	Debug.Log(bytes[i]);
}
       
Debug.Log("原始数据: " + Encoding.UTF8.GetString(bytes));
Array.Reverse(bytes);
Debug.Log("倒叙数据: " + Encoding.UTF8.GetString(bytes));
Debug.Log("转为16进制: " + BitConverter.ToString(bytes));

byte与string的转换:

string str = "f";
byte bt = Convert.ToByte(str );
str =  Convert.ToString(bt);

byte与string的16进制转换:

string str = "e";//必须为0-e
byte bt = Convert.ToByte(str,16);//从16进制的str转换为byte
str =  Convert.ToString(bt,16);//将byte转换为16进制数字的str

其他: BitConverter.ToString(bytes);将byte数组转为16进制的string,间隔符号’-’

string str = "Hello World";
byte[] bts = Encoding.UTF8.GetBytes(str);
Debug.Log(+ BitConverter.ToString(bts ));

输出:48-65-6C-6C-6F-20-57-6F-72-6C-64

经验分享 程序员 微信小程序 职场和发展