In PHP, the bindec() function is used to convert binary strings into decimal numbers and is a very practical tool when processing binary data. For example:
<?php
echo bindec("1101"); // Output 13
?>
There is no built-in function in Python with the same name as bindec() , but we can implement the same function very simply. This article will use several examples to explain in detail how to simulate PHP's bindec() function in Python.
Python's built-in function int() can convert arbitrary strings into decimal, just need to provide the correct cardinality. For example:
binary_string = "1101"
decimal_number = int(binary_string, 2)
print(decimal_number) # Output 13
This int(binary_string, 2) achieves the same effect as bindec("1101") .
To be closer to how PHP is used, we can encapsulate a function called bindec :
def bindec(binary_string):
try:
return int(binary_string, 2)
except ValueError:
raise ValueError("The entered string is not a valid binary format")
How to use it is as follows:
print(bindec("1010")) # Output 10
In PHP, bindec() treats the binary string as a complement form and converts it into a signed decimal number. For example:
echo bindec("11111111111111111111111111111111"); // Output -1
In this case, bindec() treats all 32-bit 1s as -1 (a signed integer). To achieve similar effects in Python, we need to manually judge the symbol bits:
def bindec_signed(binary_string):
length = len(binary_string)
value = int(binary_string, 2)
if binary_string[0] == '1':
# Complement to sign
value -= 1 << length
return value
Example:
print(bindec_signed("11111111111111111111111111111111")) # Output -1
print(bindec_signed("10000000000000000000000000000000")) # Output -2147483648
To prevent illegal strings from entering, we can first verify that the string is in pure binary format:
def is_valid_binary(s):
return all(c in '01' for c in s)
Use in combination:
def bindec_safe(binary_string):
if not is_valid_binary(binary_string):
raise ValueError("Illegal binary string")
return int(binary_string, 2)
To facilitate you to test these codes on web pages, you can use an online Python execution environment, for example:
You just need to copy the above code to a web page to run to get the results, which is very convenient for debugging.
Although Python does not have a built-in bindec() function, through the int() function and simple logical processing, we can completely simulate this function in PHP, and even make it more powerful:
The basic functions can be realized by int(binary, 2) ;
If you want to simulate PHP's complement behavior, you can use bindec_signed() ;
Adding exception and validity handling can improve robustness.
I hope this tutorial can help you successfully migrate the relevant logic of bindec() in cross-language development.