c# 进制转换-续

//将16进制的字符串转为byte数组

string str = "0C9C17AB";
string tmpstr = "";
byte[] buf;
if (str.Length%2!=0)
{
  str = "0"+str;
}
buf=new byte[str.Length/2];
for (int i = 0; i < str.Length/2; i++)
{
  tmpstr= str.Substring(i*2,2);
  buf[i] =(byte)(Convert.ToInt32(tmpstr,16));//16表示前面值的基数。
}

//将byte数据转为16进制字符串

byte[] buf = new byte[4];
buf[0] = 0x0C;
buf[1] = 0x9C;
buf[2] = 0x17;
buf[3] = 0xAB;
for (int i = 0; i < buf.Length; i++)
{
  string str= Convert.ToString(buf[i], 16);//两个转换都可以,推荐使用下面的方法。
  str= buf[i].ToString("x2");
}

猜你喜欢

转载自www.cnblogs.com/zhengxia/p/11809118.html