How to save 4 char in unsigned int using bitwise operation?

I would like to save 4 char (4 bytes) in an unsigned int.

+5
source share
4 answers

You need to shift the bit of each char, then OR combine them into an int:

unsigned int final = 0;
final |= ( data[0] << 24 );
final |= ( data[1] << 16 );
final |= ( data[2] <<  8 );
final |= ( data[3]       );

This uses an array of characters, but it is the same principle no matter how the data arrives. (I think I got shifts to the right)

+5
source

Another way to do this:

#include <stdio.h>
union int_chars {
    int a;
    char b[4];
};
int main (int argc, char const* argv[])
{
    union int_chars c;
    c.a = 10;
    c.b[0] = 1;
    c.b[1] = 2;
    c.b[2] = 3;
    c.b[3] = 4;
    return 0;
}
+3
source

You can do it like this (not bitwise, but maybe simpler):

unsigned int a;
char *c;

c = (char *)&a;
c[0] = 'w';
c[1] = 'o';
c[2] = 'r';
c[3] = 'd';

Or, if you want to be sized, you can use:

unsigned int a;
a &= ~(0xff << 24); // blank it
a |= ('w' << 24); // set it
// repeat with 16, 8, 0

If you do not clear it first, you may get a different result.

0
source

Simpler, better:

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

All Articles