Ad space (banner)
🐍Python Lessons
Lesson 63 / 69

Converting Number Bases (binary, hex)

This lesson covers converting numbers between bases in Python — binary and hexadecimal — so you can understand the basics of base conversion. It's written for anyone searching "Python base conversion bin hex".

bin() and hex() convert a number into a binary or hexadecimal string. In reverse, int(string, base) converts a string in that base back into a decimal number. "Base" refers to how many digits make up a single place value — 10 for decimal, 2 for binary, 16 for hexadecimal.

The sample code converts the number 42 into a binary string with bin() and a hexadecimal string with hex(). Going the other way, int("101010", 2) converts the binary string "101010" back to decimal 42, letting you confirm the conversion round-trips correctly.

A common beginner mistake is not knowing why the results of bin() and hex() carry a "0b" or "0x" prefix. This is Python's way of indicating "this is a binary/hexadecimal string" — if you only want the digits themselves, you'll need to slice the prefix off.

Computers work internally in binary, and color codes are commonly written in hexadecimal, so this kind of base-conversion knowledge is useful across programming in general. If you need octal too, oct() extends the same idea to another base.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)