How do i get the lower 8 bits of int?

前端 未结 4 585
佛祖请我去吃肉
佛祖请我去吃肉 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:19

    You can test if a particular bit is set in a number using << and &, ie:

    if (num & (1<<3)) ...

    will test if the fourth bit is set or not.

    Similarly, you can extract just the lowest 8 bits (as an integer) by using & with a number which only has the lowest 8 bits set, ie num & 255 or num & 0xFF (in hexadecimal).

提交回复
热议问题