I have this hex code F0C2CA89012A04008C0000000000000000000000 from the device. This hex code shows the value of the water drops.
In my python code
msg = F0C2CA89012A04008C0000000000000000000000
msg_counters = bytes.fromhex(msg)[5:20]
# output: b'*x04x00x8cx00x00x00x00x00x00x00x00x00x00x00'
msg_counters_int = int.from_bytes(msg_counters)
# output: 218157641024778742068286256301735936
bin_string = '{:0120b}'.format(msg_counters_int)
print(bin_string)
this print the value of bits. These bits shows the value of water
001010100000010000000000100011000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00101 = 5
01000 = 8
00010 = 2
I’m trying to convert the code to PHP and I’m stuck in int.from_bytes
from python. I don’t know how to convert the value.
In my PHP code
$a = hex2bin("F0C2CA89012A04008C0000000000000000000000");
$b = substr($a, 5, 20);
// output: b"*x04x00Œx00x00x00x00x00x00x00x00x00x00x00"
I tried to use unpack
functionality but it doesn’t show the correct value
2
Answers
To convert this Python code into PHP, you need to handle hexadecimal string manipulation, byte slicing, and integer conversion. Here’s how you can achieve the equivalent in PHP:
Python Code
Equivalent PHP Code
Explanation:
Hex to Binary Conversion:
hex2bin(substr($msg, 5, 30))
converts the relevant part of the hexadecimal string to binary data.substr($msg, 5, 30)
extracts the substring starting from the 6th character (index 5) and with a length of 30 characters.Binary to Integer Conversion:
bin2hex($msg_counters)
converts binary data to hexadecimal.gmp_init(bin2hex($msg_counters), 16)
initializes a GMP (GNU Multiple Precision) number from the hexadecimal string, since PHP’s integer type might not handle very large numbers.Integer to Binary String:
gmp_strval($msg_counters_int, 2)
converts the GMP number to a binary string.str_pad(..., 120, '0', STR_PAD_LEFT)
ensures the binary string has leading zeros to match the 120-bit length.This PHP code snippet provides an equivalent result to the Python code, converting the specified segment of a hexadecimal string into a binary string with leading zeros.
Here is an alternative solution that doesn’t rely on the GMP extension, but on the standard
base_convert()
function. For every byte, the two hex digits are extracted from the input string and converted to base 2:Output: