You can first convert the string to a byte array using an appropriate encoding (see Encoding.GetEncoding
) then you can use BitConverter.ToInt32
to convert the byte array to an integer.
string s = "ABCD";
byte[] bytes = encoding.GetBytes(s); /* Use the correct encoding here. */
int result = BitConverter.ToInt32(bytes, 0);
Result:
1145258561
To get back the string from the integer you simply reverse the process:
int i = 1145258561;
byte[] bytes = BitConverter.GetBytes(i);
string s = encoding.GetString(bytes);
Result:
ABCD
Note that BitConverter class gives a result which is dependant on the endianness of the machine it is running on. If you want the code to be platform independent you could look at EndianBitConverter in Jon Skeet's MiscUtil library.
Performance
I tested the performance of three implementations:
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;
}
Bit shifting
int convert3(string key)
{
int val = 0;
for (int i = 3; i >= 0; i--)
{
val <<= 8;
val += (int)key[i];
}
return val;
}
Loop unrolled
int convert4(string key)
{
return (key[3] << 24) + (key[2] << 16) + (key[1] << 8) + key[0];
}
Results
Biggest is best performance:
Method Iterations per second
------------------------------------
Math.Pow 690000
BitConverter 2020000
Bit shifting 4940000
Loop unrolled 8040000
Conclusion
If performance is critical then writing your own method to do bit shifting gets the best performance. Using the standard class BitConverter is probably fine for most situations where performance is not critical (assuming that you don't mind that it only works on little endian computers).