Back to Blog
Python

Python int Base Conversion: Using int() with Different Bases

python int base conversion: Learn how Python's int() converts strings and numbers between bases, with syntax, error handling, and edge cases for base 2 to 36.

int()base conversionradixnumber parsingPython
Python code showing int() with base parameter converting binary and hexadecimal strings to decimal integers.

When you call int('1010', 2) in Python, you get 10. The second argument, base, controls how the string is interpreted. This is the essence of python int base conversion: int() can parse strings in any base from 2 to 36, and it can also infer the base from common prefixes like 0b, 0o, or 0x when you pass base=0. Understanding how this works is important for reading configuration files, parsing network protocols, or handling data that uses non-decimal representations.

What int() Does with a Base Parameter

The int() constructor has the signature int(x, base=10). When x is a string, base determines the numeral system used for parsing. If x is not a string (for example, a float or another integer), base is ignored and the value is truncated toward zero. This means the base parameter only matters when the first argument is a string or bytes-like object.

# String with base 2 print(int('1010', 2)) # 10 # String with base 16 print(int('ff', 16)) # 255 # Non-string: base is ignored print(int(3.99, 2)) # 3 (truncated, base ignored)

The base parameter is optional. Without it, int('1010') assumes base 10 and returns 1010. This is a common source of confusion when developers forget to specify the base for binary or hexadecimal strings.

Valid Base Values and Digit Ranges

Python accepts any integer base from 2 to 36 for the base parameter. The digits used are 0-9 for values 0 through 9, and a-z (or A-Z) for values 10 through 35. The conversion is case-insensitive, so 'ff' and 'FF' both parse to 255 in base 16.

print(int('z', 36)) # 35 print(int('Z', 36)) # 35

If you pass a base outside the range 2–36, Python raises a ValueError. The only exception is base=0, which has special behavior described in the next section.

Base 0: The Special Case

When base is 0, Python does not treat the string as base 10. Instead, it infers the base from the string's prefix:

  • 0b or 0B → base 2
  • 0o or 0O → base 8
  • 0x or 0X → base 16
  • No prefix → base 10

This is useful when you want to parse numbers that may come from different sources and carry their own prefix, such as literals in source code or configuration values.

print(int('0b1010', 0)) # 10 print(int('0o17', 0)) # 15 print(int('0xff', 0)) # 255 print(int('42', 0)) # 42 (decimal)

Note that base=0 only recognizes these specific prefixes. A string like '010' with base 0 is interpreted as decimal 10, not octal. This differs from some other languages where a leading zero implies octal. Python 3 removed that ambiguity.

Handling Invalid Input and Errors

If the string contains digits that are not valid for the given base, int() raises a ValueError. For example, int('2', 2) fails because 2 is not a valid binary digit. Similarly, an empty string or a string with only whitespace raises ValueError regardless of base.

try: int('2', 2) except ValueError as e: print(e) # invalid literal for int() with base 2: '2' try: int('', 10) except ValueError as e: print(e) # invalid literal for int() with base 10: ''

The error message includes the base and the offending string, which helps with debugging. It's important to catch ValueError when converting untrusted input, because malformed strings will otherwise crash your program.

Practical Examples: Binary, Hex, Octal, and Custom Bases

Beyond the standard bases, int() can parse numbers in any base up to 36. This is handy for domain-specific encodings, such as base-32 or base-36 identifiers.

# Binary print(int('1101', 2)) # 13 # Hexadecimal print(int('deadbeef', 16)) # 3735928559 # Octal print(int('755', 8)) # 493 # Base 36 (alphanumeric) print(int('python', 36)) # 199473889

You can also use underscores as digit separators in the string, just like in Python literals. This improves readability for long numbers.

print(int('0x_FF_00', 16)) # 65280

Negative numbers are handled with a leading minus sign. The base applies to the absolute value, and the sign is preserved.

print(int('-101', 2)) # -5

Performance and Maintainability Considerations

int() is implemented in C and is efficient for one-off conversions. If you are converting many strings in a loop, the overhead is minimal compared to the parsing work itself. There is no need to precompile or cache anything for standard conversions.

However, maintainability can suffer when you rely on base=0 for input that may not have a prefix. It makes the code less explicit. For clarity, specify the base explicitly when you know the expected format. For example, if you are parsing a binary protocol, use int(data, 2) rather than int(data, 0) to avoid surprises if the data lacks a 0b prefix.

Another consideration is that int() does not handle non-string inputs with a base. If you accidentally pass a float or an integer, the base is silently ignored, which can hide bugs. Always ensure the first argument is a string when you intend to use a base.

Common Pitfalls and How to Avoid Them

One frequent mistake is forgetting the base for binary or hexadecimal strings. int('1010') returns 1010, not 10. Always include the base when the string is not decimal.

Another pitfall is assuming that leading zeros in a string imply octal. In Python 3, int('010', 10) returns 10, and int('010', 8) returns 8. There is no automatic octal detection unless you use base=0 with a 0o prefix.

Also, be careful when using base=0 with strings that contain a leading zero but no prefix. As mentioned, int('010', 0) returns 10, not 8. If you need to support legacy octal notation, you must strip the leading zero or handle it manually.

Finally, remember that the base parameter only works with strings. If you need to convert an integer to a string in another base, use format(value, 'b') or bin(), oct(), hex(), or format(value, 'x') — not int(). The int() function is for parsing, not formatting.

python int base conversion: Practical Usage and Code Example | RYUSLOG DEV