1

How can I compare a int number with hexadecimal and binary number?

Is there any other methods available other than I found below:

if b'\xFF'[0] == 255:
    print("yes")

if bin(b'\xFF') == bin(255)
    print("yes")

Above is doing some sort of calls and conversions. I would be surprised that if it is not possible to define a number with any input format(binary, hex, decimal) and that is still the same number for the compiler.

Almost any compiler, I know so far, can represent a number with different notations, but no way in Python, like this one:

if 255 == 0xFF
    print("yes")
2
  • 2
    "but no way in Python, like this one:" — did you try it? What happened when you tried it? Commented Nov 18 at 22:41
  • This question would be a better resource if you simply condensed the whole thing down to "How to get if 255 == 0xFF comparison to work in Python?" Commented Nov 20 at 3:01

2 Answers 2

7

This is valid expression. You just missed ":" at the end of if statement

if 255 == 0xFF:
 print("yes")
Sign up to request clarification or add additional context in comments.

Comments

5

int - hex (Integer - Hexadecimal) comparison:

You may use hex() to convert int value to hex as:

>>> hex(255)
'0xff'

Example for comparing the hex value with int can be done as:

>>> hex(255) == '0xff'
True

OR, use int() with base 16 to convert hex to int:

>>> int('0xff', 16)
255

Now this int can be compared with hex as:

>>> int('0xff', 16) == 255
True

Also, Hex number without quotes (quotes denotes str) is automatically convert to int by Python interpreter. For example:

>>> 0xff
255

Hence, you may also do direct comparison as:

>>> 255 == 0xff  # `0x` at the start denotes hexa-decimal number
True

int - bin (Integer - Binary) comparison:

You may use bin() to convert int value to binary as:

>>> bin(5)
'0b101'

Here's the example comparing int with bin value:

>>> bin(5) == '0b101'
True

OR, use int() with base 2 to convert bin to int:

>>> int('0b101', 2)
5

Using this, comparison of binary with int can be done as:

>>> int('0b101', 2) == 5
True

Python interpreter converts quote-less binary number to int:

>>> 0b101   # `0b` at the start denotes binary number
5 

Hence, you may compare int with binary as:

>>> 5 == 0b101
True

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.