将4个字符串转换为int32

有没有一种快速的方法将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字符串字符串写入整数指针位置。

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

结果

最大的是最佳表现:

方法每秒迭代次数
 ------------------------------------
 Math.Pow 690000
 BitConverter 2020000
位移4940000
循环展开8040000

结论

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

使用字节和BitConverter:

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

请注意,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已经建议)。

更简单,更好:

 /* ** Made by CHEVALLIER Bastien ** Prep'ETNA Promo 2019 */ #include  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; }