Built-in Conversion Methods
int() Function
The int() function is the primary tool for base conversion in Python:
## Convert from different bases to decimal
binary_num = int('1010', 2) ## Binary to Decimal
hex_num = int('2A', 16) ## Hexadecimal to Decimal
octal_num = int('52', 8) ## Octal to Decimal
print(binary_num) ## Output: 10
print(hex_num) ## Output: 42
print(octal_num) ## Output: 42
Advanced Conversion Techniques
Custom Base Conversion Function
def convert_base(number, from_base=10, to_base=2):
"""
Convert numbers between arbitrary bases
"""
## Convert to decimal first
decimal_num = int(str(number), from_base)
## Convert decimal to target base
if to_base == 10:
return decimal_num
digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
if decimal_num == 0:
return 0
result = []
while decimal_num > 0:
decimal_num, remainder = divmod(decimal_num, to_base)
result.append(digits[remainder])
return ''.join(result[::-1])
## Example usage
print(convert_base(42, 10, 2)) ## Decimal to Binary
print(convert_base(42, 10, 16)) ## Decimal to Hexadecimal
Conversion Methods Comparison
| Method |
Pros |
Cons |
int() |
Simple, built-in |
Limited to standard bases |
| Custom Function |
Flexible, supports any base |
More complex implementation |
format() |
Concise string formatting |
Less intuitive |
## Using format() method
decimal_num = 42
## Binary representation
binary_str = f'{decimal_num:b}'
print(binary_str) ## Output: 101010
## Hexadecimal representation
hex_str = f'{decimal_num:x}'
print(hex_str) ## Output: 2a
## Octal representation
octal_str = f'{decimal_num:o}'
print(octal_str) ## Output: 52
Handling Large Number Conversions
## Converting large numbers
large_number = 1000000
print(f"Large number in binary: {large_number:b}")
print(f"Large number in hex: {large_number:x}")
graph TD
A[Decimal Number] --> B{Conversion Method}
B --> |int()| C[Standard Base Conversion]
B --> |Custom Function| D[Flexible Base Conversion]
B --> |format()| E[String Formatting]
Best Practices
- Choose the right conversion method based on your specific use case
- Handle potential conversion errors
- Be aware of performance implications for large numbers
At LabEx, we recommend mastering these conversion techniques to enhance your Python programming skills and understand low-level data representations.