How can I access a specific group of bits from a variable?

前端 未结 4 1011
梦谈多话
梦谈多话 2021-02-06 06:58

I have a variable with \"x\" number of bits. How can I extract a specific group of bits and then work on them in C?

4条回答
  •  太阳男子
    2021-02-06 07:45

    work on bits with &, |. <<, >> operators. For example, if you have a value of 7 (integer) and you want to zero out the 2nd bit:

    7 is 111

    (zero-ing 2nd bit AND it with 101 (5 in decimal))

    111 & 101 = 101 (5)

    here's the code:

    #include 
    
    main ()
    {
        int x=7;
    
        x= x&5;
        printf("x: %d",x);
    
    }
    

    You can do with other operators like the OR, shift left, shift right,etc.

提交回复
热议问题