Access bits in a char in C

前端 未结 5 1630
别跟我提以往
别跟我提以往 2020-12-09 18:10

I have a hex number 0x37 and its binary representation is 0011 0111. How do I access the first 2 bits of the binary representation which is \"11\"? How do I use bit shifting

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 18:47

    This is the easiest function to use, I don't want others to struggle for a long time before getting something similar to this -

    char get_bits(char a, char no_of_bits)
    {
        return a & ((no_of_bits << 1) - 1);
    }
    char a = 0x37;
    char b = get_bits(a, 2);
    

    Hope it helps someone in future

提交回复
热议问题