我想将十六进制转换为等效的二进制。我试过的代码如下:
string hex_addr = "0001A000";
string bin_value = Convert.ToString(Convert.ToInt32(hex_addr, 16), 2);
这将截断前导零。我如何实现这一目标?
尝试关注(来自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();
}
您可能需要按照此链接中的建议使用 PadLeft
bin_value.PadLeft(32, '0')
只需使用 PadLeft( , ):
string strTemp = System.Convert.ToString(buf, 2).PadLeft(8, '0');
这里 buf 是你的字符串 hex_addr,strTemp 是结果。8 是您可以更改为所需长度的二进制字符串的长度。