当前位置:网站首页>C# 40. Byte[] to hexadecimal string

C# 40. Byte[] to hexadecimal string

2022-06-26 05:10:00 lljss2020

1. Code
//byte[] turn 16 Base number 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 Base number string turn 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. test
byte[] a = new byte[] {
    0x13,0xAB,0xEF };
string str = BytesToHexString(a,0,3);
byte[] b = StringToHexbytes(str);

 Insert picture description here

原网站

版权声明
本文为[lljss2020]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260501538663.html