Aren13GamerZ
Aren13GamerZ

Reputation: 27

Bitwise operations in binary format in python

My program has two vars named: IP and MASK. Those variables contain numbers in binary format, for instance: IP = "11100001" and MASK = "11000000".

I'm performing an AND operation like this: result = IP & MASK. This should give: 11000000, but instead returns 10573888. How can I make AND operations and keep the number in decimal?

I've looked around stackoverflow.com but I haven't found any similar situation, the only thing I've came across is to do manually an "algorithm" that performs this operation.

Upvotes: 1

Views: 905

Answers (2)

kabdulla
kabdulla

Reputation: 5419

IP = 0b11100001
MASK = 0b11000000
Result = bin(IP and MASK)
print(Result)

Returns 0b11000000

Pre-fixing with 0b is a common way do denote that a number is in binary format. Similarly 0x often denotes a hexadecimal number.

Upvotes: 2

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

You're entering the numbers in decimal. The bit patterns aren't what you expect:

>>> bin(11100001)
'0b101010010101111101100001'
>>> bin(11000000)
'0b101001111101100011000000'
>>> bin(11000000 & 11100001)
'0b101000010101100001000000'
>>> bin(10573888)
'0b101000010101100001000000'

To work with binary numbers, use the 0b prefix:

>>> bin(0b11000000 & 0b11100001)
'0b11000000'

Upvotes: 1

Related Questions