在 C# 中转换 int->hex->binary 时出现错误“十六进制字符串的位数为奇数”

Dil*_*ili 0 c# hex integer bytearray

目的 :

首先将整数值转换为 hexstring,然后转换为 byte[]。

例子 :

   Need to convert  int:1024 to hexstring:400 to byte[]: 00000100 00000000
Run Code Online (Sandbox Code Playgroud)

方法:

为了从整数转换为十六进制字符串,我尝试了下面的代码

    int i=1024;
    string hexString = i.ToString("X");
Run Code Online (Sandbox Code Playgroud)

我得到的十六进制字符串值为“400”。然后我尝试使用下面的代码将十六进制字符串转换为字节 []

    byte[] value = HexStringToByteArray(hexValue);

    /* function for converting hexstring to  byte array */
    public  byte[] HexStringToByteArray(string hex)
    {

        int NumberChars = hex.Length;

        if(NumberChars %2==1)
          throw new Exception("Hex string cannot have an odd number of digits.");

        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;

    }
Run Code Online (Sandbox Code Playgroud)

错误:

在这里我得到了异常“十六进制字符串不能有奇数个数字”

解决办法:??

SwD*_*n81 5

您可以强制ToString返回特定数量的数字:

string hexString = i.ToString("X08");
Run Code Online (Sandbox Code Playgroud)