C语言和指针-回顾11-位段

位段的声明和结构体的声明相同。除了:

  1. 位段成员必须声明为int,signed int,unsigned int(最好不要使用int,因为int是有符号还是没有符号是由编译器决定的)。
  2. 成员名的后面是一个冒号和一个整数,整数表示这个位段所占用的位数(bit)。

例子 1:

 

 

例子 2:

 1 #include<stdio.h>
 2 
 3 int main()
 4 {
 5     typedef struct {
 6         signed int a:2;
 7     } my_struct_1;
 8 
 9     typedef struct {
10         unsigned int a:2;
11     } my_struct_2;
12 
13     my_struct_1 test1;
14     my_struct_2 test2;
15     test1.a = 1;
16     test2.a = 1;
17     printf("%d,%d\n",test1.a, test2.a);
18 
19     test1.a += 1;
20     test2.a += 1;
21     printf("%d,%d\n",test1.a, test2.a);
22 }

Output :

1,1
-2,2

signed int的话,结果为什么是-2呢?

二进制01 + 1 = 二进制10 = -2

posted @ 2021-07-04 16:25  Erden  阅读(33)  评论(0编辑  收藏  举报