结构体定义:unsigned int type : 2;

1. C语言实现的HTTP协议的解析源码中有下面的结构体定义:

struct http_parser {
    unsigned int type : 2;
    unsigned int flags : 8;
    unsigned int state : 7;
    unsigned int header_state : 7;
    unsigned int index : 7;
    unsigned int lenient_http_headers : 1;

    unsigned int nread;
    unsigned int content_length;

    unsigned short http_major;
    unsigned short http_minor;

    unsigned int status_code : 16;
    unsigned int method : 8;
    unsigned int http_errno : 7;
    unsigned int upgrade : 1;

    void *data;
};

当前运行环境是Windows7 64位运行环境

unsigned int字节长度是4,unsigned short字节长度是2,void *字节长度是4

如果没有使用unsigned int type : 2;这种声明方法,sizeof(struct http_parser) = 12 * 4 + 2 * 2 + 4 = 56

现在这种实现:sizeof(struct http_parser) = 4 + 8 + 4 + 4 + 4 = 24

2. 理解

unsigned int type : 2; 表示type变量使用unsinged int 32位中的低两位。

该结构体中的前5个字段总共占用4个字节

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
补充完整下面代码:下面是一个完成 BMP 图像反色处理的 c 语言程序的示例: #include <stdio.h> #include <stdlib.h> // 定义 BMP 文件头的结构体 typedef struct { unsigned short int type; unsigned int size; unsigned short int reserved1, reserved2; unsigned int offset; } BMPHeader; // 定义 BMP 信息头的结构体 typedef struct { unsigned int size; int width, height; unsigned short int planes; unsigned short int bits; unsigned int compression; unsigned int imagesize; int xresolution, yresolution; unsigned int ncolours; unsigned int importantcolours; } BMPInfoHeader; // 定义调色板的结构体 typedef struct { unsigned char blue; unsigned char green; unsigned char red; unsigned char reserved; } Palette; int main(int argc, char *argv[]) { // 判断命令行参数是否合法 if (argc != 3) { printf("Usage: %s <input file> <output file>\n", argv[0]); return 1; } // 打开输入文件 FILE *input = fopen(argv[1], "rb"); if (!input) { perror(argv[1]); return 1; } // 打开输出文件 FILE *output = fopen(argv[2], "wb"); if (!output) { perror(argv[2]); return 1; } // 读取文件头 BMPHeader header; fread(&header, sizeof(BMPHeader), 1, input); // 判断文件是否是 BMP 格式 if (header.type != 0x4D42) { fclose(input); fclose(output); fprintf(stderr, "%s is not a BMP file!\n", argv[1]); return 1; } // 读取信息头 BMPInfoHeader info; fread(&info, sizeof(BMPInfoHeader), 1, input); // 判断是否是真彩色或 256 色的图像 if (info.bits != 24 && info.bits != 8) { fclose(input); fclose(output); fprintf(stderr, "Unsupported BMP image!\n"); return 1; } // 写
最新发布
02-06

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值