Guf*_*ffa 26
您可以将每个十六进制数字转换为四个二进制数字:
string binarystring = String.Join(String.Empty,
hexstring.Select(
c => Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0')
)
);
Run Code Online (Sandbox Code Playgroud)
你需要一个using System.Linq;文件的顶部才能工作.
Convert.ToString(Convert.ToInt64(hexstring, 16), 2);Run Code Online (Sandbox Code Playgroud)
也许?要么
Convert.ToString(Convert.ToInt64(hexstring, 16), 2).PadLeft(56, '0');Run Code Online (Sandbox Code Playgroud)
为什么不采用简单的方法并定义自己的映射?
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();
}
Run Code Online (Sandbox Code Playgroud)
请注意,这将保持前导零.因此"aa"将被转换为"10101010"while "00000aa"将被转换为"0000000000000000000010101010".
您可以使用此代码从十六进制字符串获取字节数组
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55694 次 |
| 最近记录: |