你可以先转换成字符串使用适当的编码字节数组(见Encoding.GetEncoding
),那么你可以使用BitConverter.ToInt32
字节数组转换为整数。
string s = "ABCD";
byte[] bytes = encoding.GetBytes(s); /* Use the correct encoding here. */
int result = BitConverter.ToInt32(bytes, 0);
结果:
1145258561
要返回从整数字符串中,你简单地恢复过程:
int i = 1145258561;
byte[] bytes = BitConverter.GetBytes(i);
string s = encoding.GetString(bytes);
结果:
ABCD
注意BitConverter类给出了一个依赖的结果不知道它运行的机器的字节顺序。如果你想让代码独立于平台,你可以在Jon Skeet的MiscUtil库中查看EndianBitConverter。
性能
我测试了三种实现的性能:
Math.Pow
int convert1(string key)
{
int val = 0;
for (int i = 0; i < 4; i++)
{
int b = (int)key[i] * (int)Math.Pow(256, i);
val += b;
}
return val;
}
BitConverter
int convert2(string key)
{
byte[] bytes = encoding.GetBytes(key);
int result = BitConverter.ToInt32(bytes, 0);
return result;
}
比特移位
int convert3(string key)
{
int val = 0;
for (int i = 3; i >= 0; i--)
{
val <<= 8;
val += (int)key[i];
}
return val;
}
环展开
int convert4(string key)
{
return (key[3] << 24) + (key[2] << 16) + (key[1] << 8) + key[0];
}
结果
最大是最佳的性能:
Method Iterations per second
------------------------------------
Math.Pow 690000
BitConverter 2020000
Bit shifting 4940000
Loop unrolled 8040000
结论
如果性能是至关重要的,那么写自己的方法做位移获得最佳性能。对于性能不重要的大多数情况(假设您不介意它仅适用于小型端计算机),使用标准类BitConverter可能没有问题。
不要忘了,在C#字符都是Unicode,并采取16位而不是8 – 2010-10-04 20:36:54