DEV Community

Cover image for Binary, Octal and Hexadecimal Values in Python
Daniel Nogueira
Daniel Nogueira

Posted on • Edited on

2 1

Binary, Octal and Hexadecimal Values in Python

Converting a decimal number to its binary, octal or hexadecimal value is easier than it looks. A simple way to do this is using the bin, oct and hex functions directly:

n = 97

print(bin(n))
print(oct(n))
print(hex(n))
Enter fullscreen mode Exit fullscreen mode

Result:

0b1100001
0o141
0x61
Enter fullscreen mode Exit fullscreen mode

Note that we have two digits of standardization at the beginning of the results, to solve this, we can slice it as follows:

n = 97

print(bin(n)[2:])
print(oct(n)[2:])
print(hex(n)[2:])
Enter fullscreen mode Exit fullscreen mode

Result:

1100001
141
61
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay