C# how convert large HEX string to binary

76,430

Solution 1

You can just convert each hexadecimal digit into four binary digits:

string binarystring = String.Join(String.Empty,
  hexstring.Select(
    c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')
  )
);

You need a using System.Linq; a the top of the file for this to work.

Solution 2

Convert.ToString(Convert.ToInt64(hexstring, 16), 2);

Maybe? Or

Convert.ToString(Convert.ToInt64(hexstring, 16), 2).PadLeft(56, '0');

Solution 3

Why not just take the simple approach and define your own mapping?

private static readonly Dictionary<char, string> hexCharacterToBinary = new Dictionary<char, string> {
    { '0', "0000" },
    { '1', "0001" },
    { '2', "0010" },
    { '3', "0011" },
    { '4', "0100" },
    { '5', "0101" },
    { '6', "0110" },
    { '7', "0111" },
    { '8', "1000" },
    { '9', "1001" },
    { 'a', "1010" },
    { 'b', "1011" },
    { 'c', "1100" },
    { 'd', "1101" },
    { 'e', "1110" },
    { 'f', "1111" }
};

public string HexStringToBinary(string hex) {
    StringBuilder result = new StringBuilder();
    foreach (char c in hex) {
        // This will crash for non-hex characters. You might want to handle that differently.
        result.Append(hexCharacterToBinary[char.ToLower(c)]);
    }
    return result.ToString();
}

Note that this will keep leading zeros. So "aa" would be converted to "10101010" while "00000aa" would be converted to "0000000000000000000010101010".

Solution 4

You can get a byte array from hex string using this code

 public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        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;
    }

Solution 5

My C++ background answer:

private Byte[] HexToBin(string pHexString)
{
    if (String.IsNullOrEmpty(pHexString))
        return new Byte[0];

    if (pHexString.Length % 2 != 0)
        throw new Exception("Hexstring must have an even length");

    Byte[] bin = new Byte[pHexString.Length / 2];
    int o = 0;
    int i = 0;
    for (; i < pHexString.Length; i += 2, o++)
    {
        switch (pHexString[i])
        {
            case '0': bin[o] = 0x00; break;
            case '1': bin[o] = 0x10; break;
            case '2': bin[o] = 0x20; break;
            case '3': bin[o] = 0x30; break;
            case '4': bin[o] = 0x40; break;
            case '5': bin[o] = 0x50; break;
            case '6': bin[o] = 0x60; break;
            case '7': bin[o] = 0x70; break;
            case '8': bin[o] = 0x80; break;
            case '9': bin[o] = 0x90; break;
            case 'A':
            case 'a': bin[o] = 0xa0; break;
            case 'B':
            case 'b': bin[o] = 0xb0; break;
            case 'C':
            case 'c': bin[o] = 0xc0; break;
            case 'D':
            case 'd': bin[o] = 0xd0; break;
            case 'E':
            case 'e': bin[o] = 0xe0; break;
            case 'F':
            case 'f': bin[o] = 0xf0; break;
            default: throw new Exception("Invalid character found during hex decode");
        }

        switch (pHexString[i+1])
        {
            case '0': bin[o] |= 0x00; break;
            case '1': bin[o] |= 0x01; break;
            case '2': bin[o] |= 0x02; break;
            case '3': bin[o] |= 0x03; break;
            case '4': bin[o] |= 0x04; break;
            case '5': bin[o] |= 0x05; break;
            case '6': bin[o] |= 0x06; break;
            case '7': bin[o] |= 0x07; break;
            case '8': bin[o] |= 0x08; break;
            case '9': bin[o] |= 0x09; break;
            case 'A':
            case 'a': bin[o] |= 0x0a; break;
            case 'B':
            case 'b': bin[o] |= 0x0b; break;
            case 'C':
            case 'c': bin[o] |= 0x0c; break;
            case 'D':
            case 'd': bin[o] |= 0x0d; break;
            case 'E':
            case 'e': bin[o] |= 0x0e; break;
            case 'F':
            case 'f': bin[o] |= 0x0f; break;
            default: throw new Exception("Invalid character found during hex decode");
        }
    }
    return bin;
}
Share:
76,430

Related videos on Youtube

jayt csharp
Author by

jayt csharp

Updated on July 09, 2022

Comments

  • jayt csharp
    jayt csharp almost 2 years

    I have a string with 14 characters . This is a hex represantation of 7bytes. I want to convert it to binary. I tried using Convert.ToString(Convert.ToInt32(hexstring, 16), 2); For small strings this works but for 14 characters it will not work because the result is too large. How can i manage this? Keep in mind that the output of the conversion should be a binary string with a lengeth of 56 characters (we must keep the leading zeros). (e.g. conversion of (byte)0x01 should yield "00000001" rather than "1")

    • Joe
      Joe almost 13 years
      Use a larger integer ToInt64 ?
    • csharptest.net
      csharptest.net almost 13 years
    • jayt csharp
      jayt csharp almost 13 years
      string lexi=("FF"); string r = null; foreach (char c in lexi) { r = r + Convert.ToString(Convert.ToInt32(c, 16), 2); } Console.Write(r); i tried this but apparently there is something wrong
    • jayt csharp
      jayt csharp almost 13 years
      Actually i did it! foreach (char c in lexi) { string voithitiko = null; voithitiko = Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2); while (voithitiko.Length!=4 ) { voithitiko="0"+voithitiko; } olotoMEbinary = olotoMEbinary + voithitiko; }
  • Ry-
    Ry- almost 13 years
    @jayt: Can you say why not? A 64-bit integer, as the name implies, has space for 8 bytes (or 7 and 7/8), and you only need 7...
  • Ry-
    Ry- almost 13 years
    @jayt: If it's because of the leading zero problem, I thought you knew about PadLeft if you're already using it for the ones that fit in 32-bits? Anyways, edited answer.
  • JohnChris
    JohnChris over 7 years
    Argument 2: cannot convert from 'System.Collections.Generic.IEnumerable<string>' to 'string[]'
  • Guffa
    Guffa over 7 years
    @JohnChris: Then you are using a version of the framework that doesn't have the String.Join(string, IEnumerable<string>) overload. You can add a .ToArray() to the .Select(...) to fix that.