# Extracting high and low bytes from long

I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.

``````#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)
``````

The first line i clearly understood like this, please make corrections if i am wrong.

``````32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100
``````

by right shifting last 16 bits we will arrive at

``````32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010
``````

I am not able to interpret the second line.

``````#define lowWord(w) ((w) & 0xffff)
``````

I would be very grateful if some body explain how the above line of code works? Thanks.

## 2 Answers

The second line masks off the top two bytes using a bitwise AND.

When you use a bitwise AND it follows the normal rules for any boolean truth table. 1 & 1 = 1, 1 & 0 = 0... Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved. In this way you can extract the lower two bytes out of the four byte long.

• So 0x0000FFFF is a hexadecimal representation of 0000 0000 0000 0000 1111 1111 1111 1111 – the_parzival Oct 26 '15 at 14:20
• Yes. We use hex because it's much more easily digested when inspected visually. :) Binary gets really long really fast. – David Hoelzer Oct 26 '15 at 16:25

An alternative way of seeing the two operations is through the operators "integer division" and "reminder of the integer division".

In a more generic fashion:

`#include <limits.h>`

```#define highBits(value, number_of_high_bits) \ (value / (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))```

```#define lowBits(value, number_of_high_bits) \ (value % (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))```

This will work regardless the number of bits used for `value` and with an arbitrary number of `high_bits` to either keep or shave.