You can first convert a string to an array of bytes using the appropriate encoding (see ) then you can use to convert an array of bytes to an integer. Encoding.GetEncoding BitConverter.ToInt32
string s = "ABCD";
byte[] bytes = encoding.GetBytes(s);
int result = BitConverter.ToInt32(bytes, 0);
Result:
1145258561
To return a string from an integer, you simply modify the process:
int i = 1145258561;
byte[] bytes = BitConverter.GetBytes(i);
string s = encoding.GetString(bytes);
Result:
ABCD
, BitConverter , , . , , EndianBitConverter Jon Skeet MiscUtil .
:
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;
}
Loop unrolled
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, , , (, , ).