1

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.

0

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

I wanted exactly this. Thanks a lot for the answer.
1

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'

1 Comment

Thanks, this explanation clarificated a lot of things.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.