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?

1
  • 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. Commented Nov 26, 2012 at 7:57

3 Answers 3

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had used this in one of my projects.
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.

Comments

0

You may need to PadLeft as suggested in this link

bin_value.PadLeft(32, '0')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.