1

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

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

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

4

3 回答 3

3

尝试关注(来自SO 链接

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();
}
于 2012-11-26T07:51:44.937 回答
0

您可能需要按照此链接中的建议使用 PadLeft

bin_value.PadLeft(32, '0')
于 2014-05-20T16:09:13.787 回答
0

只需使用 PadLeft( , ):

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

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

于 2014-03-03T15:23:09.640 回答