hexdec is a built-in function in PHP to convert hexadecimal strings into corresponding decimal numbers. It is very simple to use:
int hexdec ( string $hex_string )
$hex_string is the input hex string, case-insensitive;
The return value is the corresponding decimal integer.
When the sensor sends data through a communication interface (such as serial port, I2C, SPI, etc.), in order to save transmission bandwidth and facilitate analysis, hexadecimal encoding is often used to represent the data content of each byte. For example, the temperature value returned by the sensor may be 0x1A , corresponding to 26 in decimal.
Suppose we receive a string of hexadecimal strings from the sensor, representing different measurements of the sensor, with each two characters representing one byte. The following is a PHP code to demonstrate how to use hexdec to parse and calculate the temperature value.
<?php
// Simulate the hexadecimal data returned by the sensor,Two characters in a group represent a byte
$hexData = "1A3F0B";
// Take the first byte '1A',Convert to decimal
$tempHex = substr($hexData, 0, 2);
$tempDec = hexdec($tempHex);
echo "Sensor temperature value(Decimal):" . $tempDec; // Output:26
?>
In this example, hexdec('1A') returns 26, indicating that the temperature value is 26 degrees (specific units are defined according to the sensor).
Usually the data packet returned by the sensor contains multiple fields, such as:
2 bytes temperature
2 byte humidity
1 byte status code
Suppose the packet is a hexadecimal string like this:
$packet = "00FA007D01";
Explained as:
Temperature: 00FA (hexadecimal)
Humidity: 007D (hexadecimal)
Status code: 01
We can use hexdec to analyze one by one with substr :
<?php
$packet = "00FA007D01";
$temperatureHex = substr($packet, 0, 4);
$humidityHex = substr($packet, 4, 4);
$statusHex = substr($packet, 8, 2);
$temperature = hexdec($temperatureHex); // 250
$humidity = hexdec($humidityHex); // 125
$status = hexdec($statusHex); // 1
echo "temperature:" . $temperature . "\n";
echo "humidity:" . $humidity . "\n";
echo "Status code:" . $status . "\n";
?>
Data range : hexdec returns a floating point number. If the number is too large (exceeding the PHP integer range), it needs to be handled with other methods, such as using GMP or BCMath extension.
Data format : Make sure that the string entered to hexdec contains only legal hex characters (0-9, af, AF).
No case effect : hexdec is not case sensitive, and the results of hexdec('1A') and hexdec('1a') are the same.