Reputation: 407
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?
Upvotes: 2
Views: 2480
Reputation: 1083
You may need to PadLeft as suggested in this link
bin_value.PadLeft(32, '0')
Upvotes: 0
Reputation: 2233
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.
Upvotes: 0
Reputation: 30698
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();
}
Upvotes: 3