Usage Example for Bit Function?

Can someone give me an example of this function is to be used? is it similar to bitRead()? The reference doesn't seem have an usage example...

The sign bit of an integer is bit 15 (counting 0..15 = 16 bits). If you want to test if this bit is set one could do so in the following way:

int nr = -25;
if ((nr & bit(15)) == bit(15)) Serial.println("negative");

Another purpose is if one reads from a register e.g. a thermometer with an alarmflag at bit pos 4

byte b = ReadRegisterFromThermometer();
if (b & bit(4) == bit(4)) // then alarm !

A more complex example is if one writes to a rigister where every bit has a different meaning.

byte b = bit(7) | bit(3) | bit(1) | bit(0); // the or operation will merge the bits set.
WriteRegister(b);

Often the code is written without the bit() function with hexadecimal values directly as follows:
if ((nr & 0x80) == 0x80) Serial.println("negative");

if ((nr & bit(15)) == bit(15))

Can you explain the condition here in plain english? i get confused by the and operator..

as i understand it you use the variable name followed by a bitwise and operator and the bit function to get the value of a specific bit - is this correct?

and what does the '==bit(15)' signify?

i get confused by the and operator..

A B &
0 0 0
0 1 0
1 0 0
1 1 1

if ((nr & bit(15)) == bit(15))

Can you explain the condition here in plain english? i get confused by the and operator..

Work from the inside out. nr & bit(15) will produce a 16 bit value that has the uppermost bit set (the rest will be zero) if the value of nr is negative or zero if the value of nr is zero or positive. Take that variable and test it for equality with another value (bit(15)) which is binary 1000000000000000. In this example it will test true.

Jim.

if ((nr & bit(15)) == bit(15))

You must write the numbers in their binary (bit) format and do a bit-and as AWOL explained

nr       1000 0000 1111 1111
bit(15)  1000 0000 0000 0000
 &       ---------------------
          1000 0000 0000 0000

the result is bit(15) again that is why it is compared to bit(15). If it was not equal the sign bit wasn't set so zero or positive number.

Or, to test if the sign bit is set, you could just do

if (n < 0)

but maybe that wouldn't be so much fun!

Thanks a tonne everyone.. that clears is up..