Binary, octal and hexadecimal values in Python
Binary representation
Prefixed with
0b or
0B:
x = 0b111
Octal representation
Prefixed with
0o or
0O:
y = 0o77
Hexadecimal representation
Prefixed with
0x or
0X:
z = 0xff
Converting int to binary, octal and hexadecimal strings representation
For this, there are functions
bin(),
oct() and
hex().
Convert to binary:
>>> bin(13)
'0b1101'
Convert to octal:
>>> oct(98)
'0o142'
Convert to hexadecimal:
>>> hex(367)
'0x16f'
Converting binary, octal and hexadecimal strings to int
For this, you need to specify base to
int() function
Convert binary string to int:
>>> print(int('0b1101', 2))
13
Convert octal string to int:
>>> print(int('0o142', 8))
98
Convert hexadecimal string to int:
>>> print(int('0x16f', 16))
367