Grabbing n bits from a byte

后端 未结 6 2011
走了就别回头了
走了就别回头了 2021-01-30 14:31

I\'m having a little trouble grabbing n bits from a byte.

I have an unsigned integer. Let\'s say our number in hex is 0x2A, which is 42 in decimal. In binary it looks li

6条回答
  •  梦毁少年i
    2021-01-30 15:24

    You could use bitfields for this. Bitfields are special structs where you can specify variables in bits.

    typedef struct {
      unsigned char a:5;
      unsigned char b:3;
    } my_bit_t;
    
    unsigned char c = 0x42;
    my_bit_t * n = &c;
    int first = n->a;
    int sec = n->b;
    

    Bit fields are described in more detail at http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001320000000000000000

    The charm of bit fields is, that you do not have to deal with shift operators etc. The notation is quite easy. As always with manipulating bits there is a portability issue.

提交回复
热议问题