6

I'm trying to convert the hexadecimal representation of a 64-bit number (e.g., the string "FFFFFFFFF") to binary representation ("11111...").

I've tried

string result = Convert.ToString(Convert.ToUInt64(value, 16), 2);

but this results in a confusing compiler error:

The best overloaded method match for 'System.Convert.ToString(object, System.IFormatProvider)' has some invalid arguments

Argument 2: cannot convert from 'int' to 'System.IFormatProvider'

Community
  • 1
  • 1
santBart
  • 2,466
  • 9
  • 43
  • 66
  • 1
    Take a look at http://stackoverflow.com/questions/74148/how-to-convert-numbers-between-hexadecimal-and-decimal-in-c – CodeZombie Feb 28 '12 at 13:08
  • 1
    @ZombieHunter - How is that going to help? OP is not asking about converting to decimal, but to a string representing the _binary_. – Oded Feb 28 '12 at 13:09
  • 1
    Why would using `Convert.ToInt64` not work? – Oded Feb 28 '12 at 13:10
  • 1
    64 x F(hexadecimal) with int64 gives -1, UINT gives 18446744073709551616 – santBart Feb 28 '12 at 13:16
  • 1
    @santBart: `Convert.ToString(-1L, 2)` returns `"1111111111111111111111111111111111111111111111111111111111111111"`, so even if the intermediate value is wrong, the result is same. – dtb Feb 28 '12 at 13:25

5 Answers5

10

What's wrong with the following code?

string hex = "FFFFFFFFFFFFFFFF";

// Returns -1
long longValue = Convert.ToInt64(hex, 16);

// Returns 1111111111111111111111111111111111111111111111111111111111111111
string binRepresentation = Convert.ToString(longValue, 2);

Pretty much what you wrote (only fixed the ulong to long cast), and returns what you expect.

Edit: undeleted this answer, as even if the long representation is signed, the binary representation is actually what you expect.

Aleksandar Toplek
  • 2,792
  • 29
  • 44
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • 1
    OP has `Convert.ToUInt64`, not `Convert.ToInt64` (unsigned, not signed). – Oded Feb 28 '12 at 13:07
  • 1
    @ken2k - Spot on. althought the signed long int writes as -1 it's binary representation is correct. – Dave Becker Feb 28 '12 at 13:34
  • Is there a reason that this would be considered better than the accepted answer? it appears that the accepted answer would be "safer", but this one is more voted on, so I would assume it's completely safe. – Trevor Vance Aug 11 '22 at 19:26
4

There might be a better solution, but check if this works:

public static string HexToBinary(string hexValue)
{
    ulong number = UInt64.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

    byte[] bytes = BitConverter.GetBytes(number);

    string binaryString = string.Empty;
    foreach (byte singleByte in bytes)
    {
        binaryString += Convert.ToString(singleByte, 2);
    }

    return binaryString;
}

The most convenient way would be to use Convert.ToString(Int64, Int32), but there is no overload for ulong. Another solution is Convert.ToString(UInt64, IFormatProvider) and write your own IFormatProvider. By looking at the examples I found an IFormatProvider that formats numbers in binary, octal and hex string representation: http://msdn.microsoft.com/en-us/library/system.icustomformatter.aspx. The code there looks very similar to what I provided, so I thinks its not a bad solution.

CodeZombie
  • 5,367
  • 3
  • 30
  • 37
3

The best choice is :

public static string hex2bin(string value)
        {
            return Convert.ToString(Convert.ToInt32(value, 16), 2).PadLeft(value.Length * 4, '0');
        }
Tagon
  • 85
  • 13
Mahmut EFE
  • 5,137
  • 5
  • 46
  • 56
2

Here's a brute approach, no pancy 64bit limit:

string HexStringToBinary(string hexString)
{
    var lup = 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"}};                

    var ret = string.Join("", from character in hexString
                              select lup[character]);
    return ret;
}
Pasi Savolainen
  • 2,460
  • 1
  • 22
  • 35
1

If you used this to convert the hex string into a BitArray then the task of producing the binary representation is trivial:

BitArray barray = ConvertHexToBitArray(string hexData)
var sbuild = new StringBuilder();
for (int i = 0; i < barray.Length; i++)
{
    sbuild.Append(barray[i] ? "1" : "0");
}
Console.WriteLine(sbuild.ToString());
Community
  • 1
  • 1
Candide
  • 30,469
  • 8
  • 53
  • 60