简体   繁体   English

如何使用按位运算将4个char存储到unsigned int中?

[英]How can I store 4 char into an unsigned int using bitwise operation?

我想将4个char(4个字节)存储到unsigned int中。

You need to shift the bits of each char over, then OR combine them into the int: 你需要将每个字符的位移位,然后将它们组合成int:

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

That uses an array of chars, but it's the same principle no matter how the data is coming in. (I think I got the shifts right) 它使用了一系列字符,但无论数据是如何进入的,它都是相同的原则。(我认为我的转换正确)

One more 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;
}

More simple, its 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;
}

You could do it like this (not bit-wise, but maybe more easy): 你可以这样做(不是按位,但可能更容易):

unsigned int a;
char *c;

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

Or if you want bit-wise you can use: 或者,如果你想要按位,你可以使用:

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

If you don't blank it first you might get another result. 如果你没有先删空它,你可能会得到另一个结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM