【C语言】Traps in C Bitfield

Trying to write an overlength value to a bitfield:

#include <stdio.h>

struct test
{
    char a:1;
    char b:1;
} test1;

int main() {
    printf("%d\n", sizeof(struct test));
    printf("%.2x\n", *(char *)&test1);
    test1.a = 2;
    test1.b = 1;
    printf("%.2x\n", *(char *)&test1);
    return 0;
}

The result is:

/tmp/fo0ZfcmKnf.c: In function 'main':
/tmp/fo0ZfcmKnf.c:14:11: warning: overflow in conversion from 'int' to 'signed char:1' changes value from '2' to '0' [-Woverflow]
   14 | test1.a = 2;
      |           ^
/tmp/fo0ZfcmKnf.o
1
00
02

The write operation to bitfield "a" is lost as the LSB of number "2" is 0b. Therefore, when writing an oversized number to a bitfield, only the equivalent length of bits of the bitfield will be written. Just like writing 0xFFF to an unsigned char.

相关推荐

  1. c语言)goto语句

    2024-03-15 19:24:04       63 阅读
  2. C语言makefile语法

    2024-03-15 19:24:04       35 阅读
  3. C语言逻辑语句

    2024-03-15 19:24:04       36 阅读
  4. C语言 goto语句

    2024-03-15 19:24:04       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-15 19:24:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-15 19:24:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-15 19:24:04       87 阅读
  4. Python语言-面向对象

    2024-03-15 19:24:04       96 阅读

热门阅读

  1. AIX7.2下安装python3

    2024-03-15 19:24:04       41 阅读
  2. 微服务架构 | 架构演进

    2024-03-15 19:24:04       43 阅读
  3. CISP 4.2备考之《计算环境安全》知识点总结

    2024-03-15 19:24:04       47 阅读
  4. Python常用模块06——requests

    2024-03-15 19:24:04       39 阅读
  5. 网站服务器的作用有哪些?

    2024-03-15 19:24:04       40 阅读
  6. strlen 与 sizeof 详解

    2024-03-15 19:24:04       44 阅读
  7. Vue:封装响应式数据的防抖函数

    2024-03-15 19:24:04       43 阅读
  8. 洛谷 [NOIP2003 普及组] 乒乓球

    2024-03-15 19:24:04       42 阅读
  9. Lambda 表达式

    2024-03-15 19:24:04       39 阅读