将4个字符串转换为int32

时间:2010-10-04 20:35:19

标签: 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

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

4 个答案:

答案 0 :(得分:8)

您可以先使用适当的编码将字符串转换为字节数组(请参阅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 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;
}

<强> 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可能适用于性能不是很关键的大多数情况(假设您不介意它只适用于小端计算机)。

答案 1 :(得分:3)

使用字节和BitConverter:

byte[] bytes = ...;
int i = BitConverter.ToInt32(bytes, 0)

答案 2 :(得分:2)

请注意,C#中的字符串包含Unicode字符,而不是字节。我不知道你想用这个问题解决什么样的问题,但要注意你只能将4个字节转换为32位整数。如果您对字节编码做出假设,则仅转换Unicode字符串才有意义。因此,如果您希望将文本视为Windows-1252(非常常见的Windows字符集),则首先对字符串进行编码并将字节转换为整数值。

byte[] bytes = Encoding.GetEncoding(1252).GetBytes("ABCÖ");
uint res = BitConverter.ToUInt32(bytes, 0);

结果是res == 0xD6434241(在小端机器上)。 0xD6是'Ö'的Windows-1252号码。

根据您的问题,您可能更愿意直接使用字节(Stefan Steinegger已经建议)。

答案 3 :(得分:-1)

更简单,更好:

/*
** Made by CHEVALLIER Bastien
** Prep'ETNA Promo 2019
*/

#include <stdio.h>

int main()
{
  int i;
  int x;
  char e = 'E';
  char t = 'T';
  char n = 'N';
  char a = 'A';

  ((char *)&x)[0] = e;
  ((char *)&x)[1] = t;
  ((char *)&x)[2] = n;
  ((char *)&x)[3] = a;

  for (i = 0; i < 4; i++)
    printf("%c\n", ((char *)&x)[i]);
  return 0;
}