# Python Code - Maybe Hexadecimal? - Python

TAGS :
Viewed: 9 - Published at: a few seconds ago

#### [ Python Code - Maybe Hexadecimal? ]

I'm looking through a piece of code and came across these lines:

``````1 &amp; 0x44
1 &amp; 0x11
1 &amp; 0x85
1 &amp; 0x22
1 &amp; 0x20
``````

I have run it in Python and see numbers changing but I can't understand what it is doing. Could someone explain to me what it is doing?

Thanks

The `&` here is a bitwise operator, meaning it makes more sense to view the numbers involved in binary format to understand what is a being performed.

So for 65 decimal, convert this to binary to give `1000001'.

The others numbers are in hexadecimal and convert as follows:

``````0x10 -> 10000
0x08 -> 01000
0x04 -> 00100
0x02 -> 00010
0x01 -> 00001
``````

As you have seen, the result of `65 & 0x01` is `1`, this is achieved as follows:

``````  1000001      65 in binary
& 0000001    0x10 in binary
---------
0000001    Giving 1
---------
``````

The logic for AND being:

``````AND
0 0 | 0
0 1 | 0
1 0 | 0
1 1 | 1
``````

The code is trying to determine if a single bit has been set.

The Wikipedia article on bitwise operations should help you to understand the process.

The `&` operator performs a bitwise AND operation. In short, a bitwise and takes two binary numbers, and outputs a binary number where each bit is set to 1 iff the same location in each of the other 2 numbers are also set to 1.

Ex:

``````111 & 110 = 110
101 & 110 = 100
``````

The numbers prefixed with `0x` are hexadecimal representations.

``````65   =      1000001
0x10 = 16 = 0010000
0x8  = 8  = 0001000
0x4  = 4  = 0000100
0x2  = 2  = 0000010
0x1  = 1  = 0000001
``````

So the bitwise and outputs are

``````65 & 0x10 = 0
65 & 0x8  = 0
65 & 0x4  = 0
65 & 0x2  = 0
65 & 0x1  = 1
``````

`&` Does a "bitwise and", Each bit of the output is 1 if the corresponding bit of x AND of y is 1, otherwise it's 0. For example

``````65 & 0x1
``````

gives

``````1
``````

as it performance the bitwise operation on

``````1000001 & 0000001
``````