本文主要是介绍c语言bitField,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <cstdio>void printf_bin2(void *dataPtr, int sizeOfData) {int i, j;unsigned char *p = (unsigned char *) dataPtr + (sizeOfData - 1);//p先指向num后面第3个字节的地址,即num的最高位字节地址for (i = 0; i < sizeOfData; i++) //依次处理4个字节(32位){j = *(p - i); //取每个字节的首地址,从高位字节到低位字节,即p p-1 p-2 p-3地址处for (int k = 7; k >= 0; k--) //处理每个字节的8个位,注意字节内部的二进制数是按照人的习惯存储!{if (j & (1 << k))//1左移k位,与单前的字节内容j进行或运算,如k=7时,00000000&10000000=0 ->该字节的最高位为0printf("1");elseprintf("0");}printf(" ");//每8位加个空格,方便查看}printf("\r\n");
}// A structure without forced alignment
struct Test1 {unsigned int x: 5;unsigned int y: 8;
};// A structure with forced alignment
struct Test2 {unsigned int x: 5;unsigned int : 0;unsigned int y: 8;
};int main() {printf("Size of test1 is %lu bytes\n",sizeof(struct Test1));Test1 test1{0};test1.x = 1;test1.y = 2;printf_bin2(&test1, sizeof(Test1));printf("Size of test2 is %lu bytes\n",sizeof(struct Test2));Test2 test2{0};test2.x = 1;test2.y = 2;printf_bin2(&test2, sizeof(Test2));return 0;
}
Size of test1 is 4 bytes
00000000 00000000 00000000 01000001
Size of test2 is 8 bytes
00000000 00000000 00000000 00000010 00000000 00000000 00000000 00000001
这篇关于c语言bitField的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!