簡體   English   中英

將4個字符串轉換為int32

[英]Convert a 4 char string into 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 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可能很好(假設您不介意它只適用於小端計算機)。

使用字節和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 <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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM