How to compare hex values in python

See more:

I am using an API to check for errors. When there is an error I get array of bytes. How do I compare it to the predefine hex library value? The value of the error contain 4 bytes (LSB-MSB).

Hex value 06090011 is defined as out of range.

The api will return

error(0)=17
error(1)=0
error(2)=9
error(3)=6
----------------
--------------
-------------------
My current code gives me hex value 69011 instead of 06090011. Can someone help me?


Try using hex notation:

&H06090011 = 101253137 decimal

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900

Last update on August 19 2022 21:51:34 (UTC/GMT +8 hours)

hex() function

The hex() function converts an integer number to a lowercase hexadecimal string prefixed with "0x".

Version:

(Python 3.2.5)

Syntax:

hex(x)

Parameter:

Name DescriptionRequired /
Optional
x An integer number Required

Example: Python hex() function

number = 127
print(number, 'in hex =', hex(number))

number = 0
print(number, 'in hex =', hex(number))

number = -35
print(number, 'in hex =', hex(number))

returnType = type(hex(number))
print('Return type from hex() is', returnType)

Output:

127 in hex = 0x7f
0 in hex = 0x0
-35 in hex = -0x23
Return type from hex() is <class 'str'>

Example: hex() function, representation of a float

number = 5.25
print(number, 'in hex =', float.hex(number))

number = 0.0
print(number, 'in hex =', float.hex(number))

number = 15.5
print(number, 'in hex =', float.hex(number))

Output:

5.25 in hex = 0x1.5000000000000p+2
0.0 in hex = 0x0.0p+0
15.5 in hex = 0x1.f000000000000p+3

Pictorial Presentation:

How to compare hex values in python

Python Code Editor:

Previous: help()
Next: id()

Test your Python skills with w3resource's quiz

Python: Tips of the Day

Rotating iterable by k elements:

>>> x = [1, 2, 3, 4]
>>> k = 2
>>> x[-2:] + x[:-2]
[3, 4, 1, 2]

A stroll outside the decimal system

Photo by Alexander Sinn on Unsplash

Python is known for being powerful and easy to use when it comes to math. Both its native capabilities and resourceful libraries like NumPy, Pandas, or Scikit-learn, provide developers with the necessary tools for heavy lifting numbers. But sometimes we need to step outside the decimal world and work with one of the other common number bases.

A number base is the number of digits that a system of counting uses to represent numerical values. The most prevalent number system is the decimal system, also known as base 10. In decimal, the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 represent every possible value. But computers and software developers often need to use other bases.

Of all its cousins, the decimal system invites binary, hexadecimal, and octal over for dinner the most. The others fall into that special category of cousin you avoid when you’re with friends. However, if you plan on using binary, hexadecimal, or octal you may need to brush up on your Python. They are not as clean and easy to use in Python as base 10.

Binary

Binary only uses the digits 0 and 1. From these two, it can account for every possible value, the same a the decimal system. Do you remember place values from grade school? That’s exactly how it works. In decimal, every place increases by a multiple of ten, but in binary, every position increases by a multiple of two.

Base 10 Place Values with Example Numbers of 10, 100, and 1000Base 2 Place Values

For example, 101 would represent a value of 5.

And 10101 would represent a value of 21.

Ever wonder why your network subnet mask looks something like 255.255.255.0? Because each of those numbers separated by a period is made up of an eight-digit binary number, 11111111.

We could have started this section by stating, “Binary only uses 10 digits.” If you don’t get the joke, read the explanation of how binary works again.

In Python, using binary numbers takes a few more steps than using decimal numbers. When you enter a binary number, start with the prefix ‘0b’ (that’s a zero followed by a minuscule b).

0b11is the same as binary 11, which equates to a decimal 3. It’s not hard, but it is extra work. Whenever you want to store a binary value in a variable, it will convert it to decimal for you.

number1 = 0b11

This results in the variable number1 storing a value of three. It just stores the value without indicating you’d like it represented in binary. So, when you retrieve it, you’ll get a decimal value of 3. Truthfully, Python processes all the mathematical operators independent of base, but it always returns them to you in decimal.

“But what if I want to have my numbers returned to me in binary?”

Glad you asked.

If you’d like to keep numbers in your code strictly binary, here’s a solution.

>>> num1 = "0b100"
>>> num2 = "0b110"
>>> mysum = int(num1, 2) + int(num2, 2)
>>> print(bin(mysum))
0b1010

In the code snippet above, we started by assigning a string of “0b100” to the variable num1. Next, we assigned a string of “0b110” to the variable num2. So we have two variables of type string storing the binary representation of 4 and 6, respectively.

Next, we added the two numbers. But as we did that, we converted each to an integer in base 10 using the function int(). Normally int() would throw an error given a string with a letter in it. By specifying the second parameter of 2, we instruct int() to interpret the string as a binary number. So, it stays happy.

You can use the second parameter to specify any base between 2 and 36. Bases 2 and 36 are included in the range.

After we add the two numbers together and store the result in mysum, we print the sum. But it’s been stored independent of base. When we recall it, it still wants to present it to us in decimal. So we must tell Python we want our number in binary. Using the bin() function converts the value to binary before it’s printed to the screen.

The above code gives you a clear representation of binary in Python. However, you may also use a more abbreviated version, like this.

>>> num1 = 0b100
>>> num2 = 0b110
>>> mysum = num1 + num2
>>> print(bin(mysum))

You get the same result. The sole difference is how you are storing the numbers in variables num1 and num2. If you print either variable to the screen in the first example, you will see it in binary even though it’s technically a string. In the second example, you will see a decimal unless you use bin() to convert it.

>>> num1 = "0b100"
>>> print(num1)
"0b100"
>>> num1 = 0b100
>>> print(num1)
4
>>> print(bin(num1))
0b100

Hexadecimal

Decimal uses ten digits, binary uses two digits, and hexadecimal uses sixteen digits. Since we only have the ten digits from the decimal system to use, we substitute letters for everything above the number nine. Therefore, the digits in hexadecimal are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. They represent zero through nine, then A is worth ten, B is worth eleven, C is worth twelve, D is worth thirteen, E is fourteen, and F wraps up with a value of fifteen. So, there are sixteen digits in hexadecimal. If you write that in hexadecimal, you can state, “Hexadecimal has 10 digits.”

Wait? Haven’t we seen that before? Yes. Honestly, a ‘10’ always represents the total number of digits in any base if you are writing the number in the respective number system. But it’s only funny in binary.

When denoting hexadecimal numbers in Python, prefix the numbers with ‘0x’. Also, use the hex() function to convert values to hexadecimal format for display purposes.

Our two hexadecimal code samples are similar to the ones we used for binary.

>>> hnum1 = "0x10"
>>> hnum2 = "0x10"
>>> myhsum = int(hnum1, 16) + int(hnum2, 16)
>>> print(hnum1)
"0x10"
>>> print(myhsum)
32
>>> print(hex(myhsum))
0x20
>>> hnum1 = 0x10
>>> hnum2 = 0x10
>>> myhsum = hnum1 + hnum2
>>> print(hnum1)
16
>>> print(myhsum))
32
>>> print(hex(myhsum))
0x20

Octal

Finally, the same holds for octal. Any guesses on how many digits are in the octal number system? Octal stands for eight. Right, octal contains eight digits. And instead of bin() or hex(), we use oct() to convert numbers to octal in Python. We prefix octal numbers with a zero followed by a lowercase o, like ‘0o’.

The eight digits of octal are 0, 1, 2, 3, 4, 5, 6, 7.

Let’s use the same code sample here, but we’ll use the proper notation and conversion function for octal.

>>> onum1 = "0o10"
>>> onum2 = "0o10"
>>> myosum = int(onum1, 8) + int(onum2, 8)
>>> print(onum1)
"0o10"
>>> print(myosum)
16
>>> print(oct(myosum))
0o20
>>> onum1 = 0o10
>>> onum2 = 0o10
>>> myosum = onum1 + onum2
>>> print(onum1)
8
>>> print(myosum))
16
>>> print(oct(myosum))
0o20

Conclusion

The great thing about Python is it can do nearly everything except my laundry. And I’m working on that.

The takeaways are simple:

  • Binary uses bin() and ‘0b’.
  • Hexadecimal uses hex() and ‘0x’.
  • Octal uses oct() and ‘0o’.
  • The int() function can be used to convert numbers into a base 10 integer from any base between 2 and 36 by changing the second parameter. e.g. int(number, 30)

Even though using bases outside our beloved decimal system requires a bit more effort, Python easily adapts and empowers us to go where no decimal has gone before — into the final frontier of other bases.

Rod Castor helps companies Get Analytics Right! He helps international organizations and small businesses improve their data analytics, data science, tech strategy, and tech leadership efforts. In addition to consulting, Rod also enjoys public speaking, teaching, and writing. You can discover more about Rod and his work at rodcastor.com and through his mailing list.

How do you check hex in Python?

Return Value from hex() hex() function converts an integer to the corresponding hexadecimal number in string form and returns it. The returned hexadecimal string starts with the prefix 0x indicating it's in hexadecimal form.

How do I use hex codes in Python?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.

How do you read a hex string in Python?

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

How does Python compare binary values?

Algorithm. Step 1 : Given two numbers. Step 2 : Convert both number into its binary using bin() function and remove first two characters because of bin(). Step 3 : Since binary representation of both numbers could differ in length so we will append zeroes in start of shorter string to make both string of equal length.