Python Conversion Techniques
Built-in Conversion Methods
1. int() Function Conversion
The int()
function provides the most straightforward way to convert hexadecimal to decimal:
## Basic hex to decimal conversion
hex_value = "1A3"
decimal_value = int(hex_value, 16)
print(f"Hexadecimal {hex_value} = {decimal_value} in decimal")
2. Handling Hex Prefixes
## Converting hex values with different prefixes
hex_with_prefix1 = "0x1A3" ## Typical hex prefix
hex_with_prefix2 = "0X1A3" ## Alternative prefix
decimal1 = int(hex_with_prefix1, 16)
decimal2 = int(hex_with_prefix2, 16)
Advanced Conversion Techniques
Conversion Methods Comparison
Method |
Approach |
Performance |
Flexibility |
int() |
Built-in |
High |
Excellent |
eval() |
Dynamic |
Low |
Limited |
Custom |
Manual |
Medium |
Customizable |
3. Manual Conversion Algorithm
def hex_to_decimal(hex_string):
"""Custom hex to decimal conversion"""
hex_map = {
'0': 0, '1': 1, '2': 2, '3': 3,
'4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'A': 10, 'B': 11,
'C': 12, 'D': 13, 'E': 14, 'F': 15
}
hex_string = hex_string.upper()
decimal_value = 0
power = 0
for digit in reversed(hex_string):
decimal_value += hex_map[digit] * (16 ** power)
power += 1
return decimal_value
## Example usage
result = hex_to_decimal("1A3")
print(f"Manual conversion: {result}")
Error Handling and Validation
def safe_hex_conversion(hex_value):
try:
return int(hex_value, 16)
except ValueError:
print(f"Invalid hexadecimal value: {hex_value}")
return None
## Conversion flow
```mermaid
graph TD
A[Hex Input] --> B{Valid Hex?}
B -->|Yes| C[Convert to Decimal]
B -->|No| D[Raise Error]
Benchmarking Conversion Methods
import timeit
## Comparing conversion techniques
def method1():
return int("1A3", 16)
def method2():
hex_map = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
return sum(hex_map[d] * (16 ** p) for p, d in enumerate(reversed("1A3".upper())))
## Timing comparisons
print("Built-in method:", timeit.timeit(method1, number=10000))
print("Custom method:", timeit.timeit(method2, number=10000))
Best Practices
- Use
int(hex_value, 16)
for most scenarios
- Implement error handling
- Consider performance for large-scale conversions
- Validate input before conversion
At LabEx, we recommend mastering these techniques to become proficient in hexadecimal manipulation.