简体   繁体   中英

Error “Hex string have a odd number of digits” while converting int->hex->binary in C#

Aim :

To convert a integer value first to hexstring and then to byte[].

Example :

   Need to convert  int:1024 to hexstring:400 to byte[]: 00000100 00000000

Method:

For converting from integer to hex string i tried below code

    int i=1024;
    string hexString = i.ToString("X");

i got hexstring value as "400". Then i tried converting hex string to byte[] using below code

    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;

    }

Error:

Here i got the exception "Hex String cannot have a odd number of digits"

Solution : ??

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

string hexString = i.ToString("X08");

Your code throws the exception you're seeing:

throw new Exception("Hex string cannot have an odd number of digits.");

You can improve the conversion method to also accept odd hex string lengths like this:

using System.Collections.Generic;
using System.Linq;

// ...

public  byte[] HexStringToByteArray(string hex)
    {
        var result = new List<byte>();

        for (int i = hex.Length - 1; i >= 0; i -= 2)
            {
                if (i > 0)
                    {
                        result.Insert(0, Convert.ToByte(hex.Substring(i - 1, 2), 16));
                    }
                else
                    {
                        result.Insert(0, Convert.ToByte(hex.Substring(i, 1), 16));
                    }
            }

        return bytes.ToArray();
    }

This code should iterate through the hex string from its end, adding new bytes to the beginning of the resulting list (that will be transformed into an array before returning the value). If a single digit remains, it will be treated separately.

The exception is thrown by your own code. You can make your code more flexible to accept hex strings that have an odd number of digits:

if (hex.Length % 2 == 1) hex = "0"+hex;

Now you can remove the odd/even check, and your code will be alright.

Your hex string has an odd number of digits and you are explicitly checking for that and throwing the exception. You need to decide why you put this line of code in there and whether you need to remove that in favour of other logic.

Other options are:

  1. add a "0" to the beginning of the string to make it even length
  2. force whoever is calling that code to always provide an even length string
  3. change the later code to deal with odd numbers of characters properly...

In comments you have suggested that the first is what you need to know in which case:

if(hex.Length%2==1)
    hex = "0"+hex;

Put this at the beginning of your method and if you get an odd number in then you will add the zero to it automatically. You can of course then take out your later check and exception throw.

Of note is that you may want to validate the input string as hex or possibly just put a try catch round the conversion to make sure that it is a valid hex string.

Also since it isn't clear whether the string is a necessary intermediate step or just one that you think is necessary, you might be interested in C# int to byte[] which deals with converting to bytes without the intermediate string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM