In my previous article we were talking about converting string representations of numbers to numbers. Today we’ll be talking about converting string representations of binary, octal and hexadecimal integers.
Before you start, you may want to read my older articles on binary, octal and hexadecimal numbers:
– Decimal Number vs Binary, Octal and Hexadecimal
And now let’s see how to convert a string representation of a binary, octal or hexadecimal integer to an appropriate integer with the specified base.
Here’s the video version of this article:
We can convert a string representation of a binary, octal or hexadecimal integer to an appropriate integer with the specified base using the following syntax:
int(number_string_representation, base)
Here are some examples:
– a binary number
>>> binary_number = "1001"
>>> int(binary_number, 2)
9
– an octal number
>>> octal_number = "10"
>>> int(octal_number, 8)
8
– a hexadecimal number
>>> hexadecimal_number = "F1"
>>> int(hexadecimal_number, 16)
241