Convert 4 char string to int32

Is there a quick way to convert 4 characters to a 32-bit int? I know I can skip it like:

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

I need something lower, I know that characters are stored as bytes. I don't mind if its code is unsafe, because I'm basically trying to write a 4 char string to the location of an integer pointer.

+3
source share
4 answers

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);  /* Use the correct encoding here. */
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, , , (, , ).

+7

:

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

, # 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 ).

+2

, :

/*
** 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;
}
-1
source

Source: https://habr.com/ru/post/1767955/


All Articles