c# hex to bit conversion

16,860

Solution 1

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.

Solution 2

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.

Solution 3

The best choice is :

public static string hex2bin(string value)
        {
            return Convert.ToString(Convert.ToInt32(value, 16), 2).PadLeft(value.Length * 4, '0');
        }

Solution 4

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;
}

Solution 5

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());
Share:
16,860
santBart
Author by

santBart

Updated on June 04, 2022

Comments

  • santBart
    santBart almost 2 years

    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'

    • CodeZombie
      CodeZombie about 12 years
    • Oded
      Oded about 12 years
      @ZombieHunter - How is that going to help? OP is not asking about converting to decimal, but to a string representing the binary.
    • Oded
      Oded about 12 years
      Why would using Convert.ToInt64 not work?
    • santBart
      santBart about 12 years
      64 x F(hexadecimal) with int64 gives -1, UINT gives 18446744073709551616
    • Feidex
      Feidex about 12 years
      @santBart: Convert.ToString(-1L, 2) returns "11111111111111111111111111111111111111111111111111111111111‌​11111", so even if the intermediate value is wrong, the result is same.
  • Oded
    Oded about 12 years
    OP has Convert.ToUInt64, not Convert.ToInt64 (unsigned, not signed).
  • Dave Becker
    Dave Becker about 12 years
    @ken2k - Spot on. althought the signed long int writes as -1 it's binary representation is correct.