使用C#从十六进制转换为二进制而不会丢失前导0

时间:2012-11-26 07:46:18

标签: c# asp.net .net hex

我想将十六进制转换为等效的二进制。我试过的代码如下:

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

这将截断前导零。我如何实现这一目标?

3 个答案:

答案 0 :(得分:3)

尝试关注(来自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();
}

答案 1 :(得分:0)

只需使用PadLeft(,):

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

这里buf是你的字符串hex_addr,strTemp是结果。 8是您可以更改为所需二进制字符串长度的长度。

答案 2 :(得分:0)

您可能需要按照此link

中的建议使用PadLeft
bin_value.PadLeft(32, '0')
相关问题