2

I want to convert a hexadecimal to its equivalent binary. The code I have tried is as below:

string hex_addr = "0001A000";
string bin_value = Convert.ToString(Convert.ToInt32(hex_addr, 16), 2);

This will truncate the leading zeros. How do I achieve this?

John Oxley
  • 14,698
  • 18
  • 53
  • 78
Archana B.R
  • 397
  • 3
  • 9
  • 24
  • 1
    As far as I can tell this code actually works fine when string hex_addr = "0001A000"; It outputs, "11010000000000000". It doesn't make any difference whether the hex value has leading 0s or not. – Chris Wallis Nov 26 '12 at 07:57

3 Answers3

3

Try following (from the SO link)

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();
}
Community
  • 1
  • 1
Tilak
  • 30,108
  • 19
  • 83
  • 131
0

Just use PadLeft( , ):

string strTemp = System.Convert.ToString(buf, 2).PadLeft(8, '0');

Here buf is your string hex_addr, strTemp is the result. 8 is the length which you can change to your desired length of binary string.

malajisi
  • 2,165
  • 1
  • 22
  • 18
0

You may need to PadLeft as suggested in this link

bin_value.PadLeft(32, '0')
Community
  • 1
  • 1
Justin Samuel
  • 1,063
  • 4
  • 16
  • 30