0

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: ??

Dileep
  • 2,399
  • 4
  • 26
  • 39
  • Your hex string has an odd number of digits and you are explicitly checking for that and throwing the exception... You could just add a zero to the beginning of your string if it has an odd number of digits or change the later code to cope with odd numbers of digits... Where exactly are you wanting the help? – Chris Jun 13 '12 at 13:16
  • I added exception with intention , bcoz i dont need hexStrings with odd digits. its against the logic in this code. So how can i ensure the ToString("x") always give even length string?? – Dileep Jun 13 '12 at 13:22
  • 1
    @DILi - See my answer. This ensures you get 8 hex digits no matter the int value. – SwDevMan81 Jun 13 '12 at 13:31
  • 1
    In case you don't see it among the rest of my answer then http://stackoverflow.com/questions/1318933/c-sharp-int-to-byte might be of interest - converting to bytearray without going via the string stage. – Chris Jun 13 '12 at 13:43

4 Answers4

5

You can force the ToString to return a specific number of digits:

string hexString = i.ToString("X08");
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • perfect and spot on in my case.. " string hexstring=i.ToString("x04");" is enough.. – Dileep Jun 13 '12 at 13:36
  • actually i should thank you giving me such a simple and cool answer..U deserve all your up votes..Hats off to you @SwDevMan81 – Dileep Jun 13 '12 at 13:40
3

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

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.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
1

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.

Community
  • 1
  • 1
Chris
  • 27,210
  • 6
  • 71
  • 92
  • i saw it.. if(hex.Length%2==1) hex = "0"+hex; .this will do what i need..In my case the conversion to hexstring in needed. – Dileep Jun 13 '12 at 13:46