如果你想遍歷每個字節的十六進制表示的字符串中,你可以使用以下擴展名。我把米奇的答案與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