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

发布于 2024-11-03 06:46:37 字数 35 浏览 1 评论 0原文

我想将 4 个字符(4 个字节)存储到一个无符号整数中。

I would like to store 4 char (4 bytes) into an unsigned int.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蓝眼睛不忧郁 2024-11-10 06:46:37

您需要将每个字符的位移过来,然后将它们组合成 int:

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

这使用字符数组,但无论数据如何传入,原理都是相同的。(我认为我的移位是正确的)

You need to shift the bits of each char over, then OR combine them into the 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)

赤濁 2024-11-10 06:46:37

另一种方法可以做到这一点:

#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;
}

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;
}
︶ ̄淡然 2024-11-10 06:46:37

越简单越好:

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

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;
}
风蛊 2024-11-10 06:46:37

你可以这样做(不是按位,但可能更容易):

unsigned int a;
char *c;

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

或者如果你想要按位,你可以使用:

unsigned int a;
a &= ~(0xff << 24); // blank it
a |= ('w' << 24); // set it
// repeat with 16, 8, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文