How do I specify hexadecimal and octal integers?

To specify an octal digit, precede the octal value with a zero. For example, to set the variable “a” to the octal value “10” (8 in decimal), type:

>>> a = 010
>>> a
8

Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero, and then a lower or uppercase “x”. Hexadecimal digits can be specified in lower or uppercase. For example, in the Python interpreter:

>>> a = 0xa5
>>> a
165
>>> b = 0XB2
>>> b
178

If you have the integer value in a string, you can use int with the base set to zero to convert using the above rules:

>>> int("10", 0)
10
>>> int("010", 0)
8
>>> int("0x10", 0)
16

CATEGORY: programming

 

Comment:

In Python 3.0, the octal literal prefix will be changed from '0' to '0o'. Also, a binary literal (prefix '0b') will be added.

Posted by Chris Rebert (2007-07-02)

A Django site. rendered by a django application. hosted by webfaction.