Python中不使用hex()实现十进制转十六进制及十六进制数运算方法
Hey there! No worries at all—we’ve all fumbled through hex handling in Python when starting out. Let’s break down your questions clearly:
1. Handling Hex Input for Numeric Operations
First off, a key thing to understand: Python integers don’t have a "base" stored with them. Whether you write 10, 0xa, or 0o12, they’re all the same integer value under the hood. So when you want to work with hex inputs and do math like addition, left shifts, etc., here’s the straightforward workflow:
- Take the hex string input and convert it to an integer using
int(input_str, 16) - Do all your numeric operations directly on that integer (you can even use hex literals like
0x5in your calculations if that feels more intuitive) - If you need to see or output the result in hex format, you can format it as a hex string (no need to keep it as a string for operations)
Here’s a concrete example:
# Get hex input from the user hex_input = input("Enter a hex number: ") # Convert to integer (this is where the "hex value" becomes a numeric type we can work with) num = int(hex_input, 16) # Do your operations—these work just like any integer math added = num + 0x5 # Adding hex 5 (which is decimal 5) shifted = num << 2 # Left shift by 2 bits # To view results in hex format (without relying on hex() if you prefer) print(f"Original value (hex): {num:X}") # Uppercase hex print(f"After adding 0x5: {added:x}") # Lowercase hex print(f"After left shift: {shifted:X}")
This way, you get the best of both worlds: you can perform all numeric operations seamlessly, and you can output or inspect values in hex whenever you need to.
2. Converting Decimal to Hex Without Using hex()
Absolutely feasible! There are a couple of easy ways to do this, plus you can even roll your own conversion logic if you want to understand the process:
Method 1: String Formatting (Simplest)
Use Python’s string formatting syntax to directly convert a decimal integer to a hex string:
decimal_num = 255 # Uppercase hex hex_upper = f"{decimal_num:X}" # Result: "FF" # Lowercase hex hex_lower = f"{decimal_num:x}" # Result: "ff" # Or use the format() function if you prefer hex_upper_alt = format(decimal_num, 'X')
Method 2: Manual Conversion (For Learning)
If you want to implement the conversion yourself (great for understanding how base conversion works), you can do it by repeatedly dividing the decimal number by 16 and mapping remainders to hex characters:
def decimal_to_hex(decimal_num): hex_chars = "0123456789abcdef" if decimal_num == 0: return "0" is_negative = False if decimal_num < 0: is_negative = True decimal_num = -decimal_num hex_str = "" while decimal_num > 0: remainder = decimal_num % 16 hex_str = hex_chars[remainder] + hex_str decimal_num = decimal_num // 16 return "-" + hex_str if is_negative else hex_str # Test it out print(decimal_to_hex(10)) # Output: "a" print(decimal_to_hex(255)) # Output: "ff" print(decimal_to_hex(-32)) # Output: "-20"
内容的提问来源于stack exchange,提问作者Priyanka

