How do i get the lower 8 bits of int?

前端 未结 4 577
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 19:56

Lets say I have an int variable n = 8. On most machines this will be a 32 bit value. How can I only get the lower 8 bits (lowest byte) of this in binary? Also how can i acce

4条回答
  •  自闭症患者
    2020-12-08 20:37

    The best way is to use the bit logical operator & with the proper value.

    So for the lower 8 bits:

    n & 0xFF; /* 0xFF == all the lower 8 bits set */
    

    Or as a general rule:

    n & ((1<<8)-1) /* generate 0x100 then subtract 1, thus 0xFF */
    

    You can combine with the bit shift operator to get a specific bit:

    (n & (1<<3))>>3; 
      /* will give the value of the 3rd bit - note the >>3 is just to make the value either 0, or 1, not 0 or non-0 */
    

提交回复
热议问题