Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how convert large HEX string to binary

Tags:

string

c#

hex

bin

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")

like image 311
jayt csharp Avatar asked Jul 07 '11 21:07

jayt csharp


3 Answers

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.

like image 125
Guffa Avatar answered Nov 09 '22 01:11

Guffa


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".

like image 45
configurator Avatar answered Nov 09 '22 02:11

configurator


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

Maybe? Or

Convert.ToString(Convert.ToInt64(hexstring, 16), 2).PadLeft(56, '0');
like image 13
Ry- Avatar answered Nov 09 '22 01:11

Ry-