gpt4 book ai didi

c - 如何在c中操作整数类型的位?

转载 作者:太空宇宙 更新时间:2023-11-04 05:28:04 24 4
gpt4 key购买 nike

我写了这个程序:

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

struct A {
bool a;
bool b;
bool c;
bool d;
};

struct B {
int a;
};

int main() {
struct A* pa = malloc( sizeof(struct A) );
struct B* pb = (struct B*) pa;
pa->a = 0;
pa->b = 1;
pa->c = 0;
pa->d = 0;

printf("value of pint is %i\n", pb->a);
return 0;
}

我预计它会打印 2 (0010),但输出是 256。任何人都可以帮我看看这段代码有什么问题吗?

最佳答案

I expect that it print 2 (0010) but the output is 256. Any one cloud help that what is wrong with this code?

bool 至少占用一个字节。在您的情况下,显然恰好是一个字节,并且您的平台是小端(使用 8 位 char)。所以第二个(最低有效)字节为 1,所有其他字节为 0,使得 1*256

请注意,通过 papb 进行的类型双关违反了严格的别名。

使用 union 进行可移植的双关语。

关于c - 如何在c中操作整数类型的位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16791257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com