zoukankan      html  css  js  c++  java
  • [整理]C结构实现位段(bit field)

    #include <stdio.h>
    #include <string.h>
    
    typedef struct A{
    	int a:5;
    	int b:3;
    	unsigned c:8;
    	unsigned d:8;
    } Type_A;
    
    /* VS2010, Windows XP, Debug模式下运行 */
    int main(void)
    {   
    	struct A a;
    	char s[]="12345678";
    
    	printf( "%d
    ",sizeof(Type_A) );//4
    	printf("%d
    ",sizeof(a));//4
    
    	memcpy(&a,s,3);
    	printf("%d
    ",a.a);//'1'的低位 -15
    	printf("%d
    ",a.b);//'1'的高位 1
    	printf("%d
    ",a.c-'0');//'3' 51
    	printf("%d
    ",a.d-'0');//'4' 52
    
    	return 0;
    }
    

    '1'(49)的二进制 00110001,
    a.a=10001 (-15)
    a.b=001     (1)

    由A的定义已知a.a(10001)是代表一个有符号的int型,

    先执行符号位扩展得到11110001,

    再减一得到11110000,

    再取反得到10001111,就是-15的源码了.
    所以a.a的值为-15, 同理,a.b为1。

    参考:

    http://www.cnblogs.com/bigrabbit/archive/2012/09/20/2695543.html

  • 相关阅读:
    魔术球问题
    【模板】网络最大流
    [SCOI2010]股票交易
    [SCOI2009]生日礼物
    [HAOI2007]修筑绿化带
    [HAOI2007]理想的正方形
    [USACO12MAR]花盆Flowerpot
    滑动窗口
    斐波那契公约数
    [SDOI2008]仪仗队
  • 原文地址:https://www.cnblogs.com/Benoly/p/3848643.html
Copyright © 2011-2022 走看看