Read bits individually from a byte

Hi All,
I would like to read each bit of a byte individually.
I could test each bit using bitwise & operators and a changing mask: 0000 0001, 0000 0010, etc.
But, does anyone know an easier way or a function to read a bit from a byte?
Thanks very much. :particle:

That’s pretty much how you’d do that.

It’s usually done in connection with a shift operation

// if you only want false / !false
 (someInt & (1 << bitNumber))
// if you want explicit 0 or 1
 ((someInt & (1 << bitNumber))? 1 : 0)
// or
 // no not this ((someInt >> bitNumber) & 0xFFFFFFFE), but
 ((someInt >> bitNumber) & 1)

You can wrap this in a macro and got the simples solution there

3 Likes

Thanks ScruffR - fast! And neat!

2 Likes

Thanks @ScruffR for the help!

With the 3rd one, shouldn’t it be:

(someInt >> bitNumber) & 0x00000001)

?

Yup, my bad :blush:

(corrected)