你可以先轉換成字符串使用適當的編碼字節數組(見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