将4个字符串转换为int32

Pro*_*nce 4 c#

有没有一种快速的方法将4个字符转换为32位int?我知道我可以循环通过它:

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
Run Code Online (Sandbox Code Playgroud)

我想要更低级别的东西,我知道字符存储为字节.我不介意它是否是不安全的代码,因为我基本上试图将4字符串字符串写入整数指针位置.

Mar*_*ers 8

您可以先使用适当的编码将字符串转换为字节数组(请参阅参考资料Encoding.GetEncoding),然后您可以BitConverter.ToInt32将字节数组转换为整数.

string s = "ABCD";
byte[] bytes = encoding.GetBytes(s);  /* Use the correct encoding here. */
int result = BitConverter.ToInt32(bytes, 0);
Run Code Online (Sandbox Code Playgroud)

结果:

1145258561
Run Code Online (Sandbox Code Playgroud)

要从整数中取回字符串,只需反转该过程:

int i = 1145258561;
byte[] bytes = BitConverter.GetBytes(i);
string s = encoding.GetString(bytes);
Run Code Online (Sandbox Code Playgroud)

结果:

ABCD
Run Code Online (Sandbox Code Playgroud)

请注意,BitConverter类提供的结果取决于运行它的机器的字节顺序.如果您希望代码与平台无关,您可以查看Jon SkeetMiscUtil库中的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;
}
Run Code Online (Sandbox Code Playgroud)

BitConverter

int convert2(string key)
{
    byte[] bytes = encoding.GetBytes(key);
    int result = BitConverter.ToInt32(bytes, 0);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

位移

int convert3(string key)
{
    int val = 0;
    for (int i = 3; i >= 0; i--)
    {
        val <<= 8;
        val += (int)key[i];
    }
    return val;
}
Run Code Online (Sandbox Code Playgroud)

循环展开

int convert4(string key)
{
    return (key[3] << 24) + (key[2] << 16) + (key[1] << 8) + key[0];
}
Run Code Online (Sandbox Code Playgroud)

结果

最大的是最佳表现:

Method         Iterations per second
------------------------------------
Math.Pow                      690000
BitConverter                 2020000
Bit shifting                 4940000
Loop unrolled                8040000

结论

如果性能至关重要,那么编写自己的方法来进行位移可以获得最佳性能.对于性能不重要的大多数情况,使用标准类BitConverter可能很好(假设您不介意它只适用于小端计算机).