How to create integer in Python, octal, binary hexadecimal and long integer
int literal
The integer literal are as follows:
1234, -24, 0
print 1234
print -24
print 0
The code above generates the following result.
To denote an octal literal, use 0 (or 0o) followed by a sequence of octal digits (0 to 7).
To indicate a hexadecimal literal, use 0x followed by a sequence of hexadecimal digits (0 to 9 and A to F, in either upper- or lowercase).
1, 23, 3493 # Decimal integers
01, 027, 06645 # Octal integers
0x1, 0x17, 0xDA5 # Hexadecimal integers
print 0122
print 0x9ff
print 0b1111
The code above generates the following result.
Long integer literal is ending with L
, for example 42L
.
print 42L
The code above generates the following result.
Convert String to int
car = "123"# from w w w .j ava2 s .c o m
car = int(car)
rent = int("12")
total = car + rent
print "\nGrand Total: ", total
The code above generates the following result.
The following code converts string to int with different base value.
print int('0100'), int('0100', 8), int('0x40', 16)
The code above generates the following result.
Convert to octal and hexadecimal
We can convert decimal int to octal and hexadecimal.
print oct(64), hex(64), hex(255)
The code above generates the following result.