Is there a fast way to convert 4 chars into a 32bit int? I know i can loop through it like :
string key = "ABCD";
int val = 0;
for (int i = 0; i < 4; i++)
{
int b = (int)key[i] * (int)Math.Pow(256, i);
val += b;
}
// val = 1145258561
I would like something lower level, I know the chars are stored as bytes. I don’t mind if its unsafe code because I am basically trying to write a 4 char string to an integer pointer location.
You can first convert the string to a byte array using an appropriate encoding (see
Encoding.GetEncoding) then you can useBitConverter.ToInt32to convert the byte array to an integer.Result:
To get back the string from the integer you simply reverse the process:
Result:
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
BitConverter
Bit shifting
Loop unrolled
Results
Biggest is best performance:
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).