如果你想遍历每个字节的十六进制表示的字符串中,你可以使用以下扩展名。我把米奇的答案与this结合起来。
static class StringExtensions
{
public static IEnumerable<string> ToHex(this String s) {
if (s == null)
throw new ArgumentNullException("s");
int mod4Len = s.Length % 8;
if (mod4Len != 0)
{
// pad to length multiple of 8
s = s.PadLeft(((s.Length/8) + 1) * 8, '0');
}
int numBitsInByte = 8;
for (var i = 0; i < s.Length; i += numBitsInByte)
{
string eightBits = s.Substring(i, numBitsInByte);
yield return string.Format("{0:X2}", Convert.ToByte(eightBits, 2));
}
}
}
例子:
string test = "0110011010010111001001110101011100110100001101101000011001010110001101101011";
foreach (var hexVal in test.ToHex())
{
Console.WriteLine(hexVal);
}
打印
06
69
72
75
73
43
68
65
63
6B
为什么w你是否期望'Convert.ToUInt64()'能够处理一个表示大于'UInt64'的值的字符串? – 2011-04-10 14:14:57