当前位置:网站首页>C# 40. byte[]与16进制string互转

C# 40. byte[]与16进制string互转

2022-06-26 05:02:00 lljss2020

1. 代码
//byte[]转16进制string
//0x13 0xab 0xef -> “13ABEF”
public string BytesToHexString(byte[] bytes,int offset, int length)
{
    
      string hexString = string.Empty;
      if((bytes != null) && (length != 0))
      {
    
          StringBuilder strB = new StringBuilder();
          for(int i=offset;i<length+offset;i++)
          {
    
              strB.Append(bytes[i].ToString("X2"));
          }
          hexString = strB.ToString();
      }
      return hexString;
  }

//16进制string转byte[]
//“13ABEF” -> 0x13 0xab 0xef 
public byte[] StringToHexbytes(string hexString)
{
    
    if (hexString == null) return null;
    hexString = hexString.Replace(" ","");
    byte[] returnBytes = new byte[hexString.Length/2];
    for (int i = 0; i < returnBytes.Length; i++)
    {
    
        returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); 
    }
    return returnBytes;
}
2. 测试
byte[] a = new byte[] {
    0x13,0xAB,0xEF };
string str = BytesToHexString(a,0,3);
byte[] b = StringToHexbytes(str);

在这里插入图片描述

原网站

版权声明
本文为[lljss2020]所创,转载请带上原文链接,感谢
https://blog.csdn.net/lljss1980/article/details/125462866