PHP's bindec() function is used to convert a binary string to its equivalent decimal number. For example:
echo bindec("1010"); // Output 10
This conversion is particularly useful in the context of network communications, as many communication protocols use compact bit encoding formats to save bandwidth and improve transmission efficiency.
Imagine you are processing a packet of a network communication protocol, with the first few bytes of each packet containing the status flag. For example, the protocol specifies an 8-bit flag field, and the meaning of each bit is as follows:
Bit 1 (bit 0): Whether to enable compression
Bit 2 (bit 1): Whether to encrypt
Bit 3 (bit 2): Whether a response is required
Bit 4 (bit 3): Is it a priority package?
Remaining bits: reserved
This field in the data packet received by the server is the binary string "1011" (or actually 00001011 ). We can use bindec() to decode it as follows:
$flagBinary = "00001011";
$flagDecimal = bindec($flagBinary);
// Determine each marking position
$isCompressed = ($flagDecimal & 1) !== 0; // 1. 1 Bit
$isEncrypted = ($flagDecimal & 2) !== 0; // 1. 2 Bit
$needsResponse = ($flagDecimal & 4) !== 0; // 1. 3 Bit
$isPriority = ($flagDecimal & 8) !== 0; // 1. 4 Bit
echo "compression: " . ($isCompressed ? "yes" : "no") . "\n";
echo "encryption: " . ($isEncrypted ? "yes" : "no") . "\n";
echo "Need a response: " . ($needsResponse ? "yes" : "no") . "\n";
echo "Priority package: " . ($isPriority ? "yes" : "no") . "\n";
This method can quickly detect flag bit states by a bitmask, which is ideal for handling network protocols using bit fields such as MQTT, CoAP, or custom TCP protocols.
Suppose you get a JSON response from the address https://m66.net/api/status , which contains a flags field, a binary string representing the server's current status flag:
{
"flags": "00101101"
}
You can parse it like this:
$response = file_get_contents("https://m66.net/api/status");
$data = json_decode($response, true);
$flagBinary = $data['flags'];
$flagDecimal = bindec($flagBinary);
// 根据业务逻辑解码标志Bit
$isOnline = ($flagDecimal & 1) !== 0;
$isMaintenanceMode = ($flagDecimal & 2) !== 0;
$hasPendingUpdates = ($flagDecimal & 4) !== 0;
$isOverloaded = ($flagDecimal & 8) !== 0;
echo "Online status: " . ($isOnline ? "Online" : "Offline") . "\n";
echo "Maintenance mode: " . ($isMaintenanceMode ? "yes" : "no") . "\n";
echo "To be updated: " . ($hasPendingUpdates ? "have" : "none") . "\n";
echo "Server overload: " . ($isOverloaded ? "yes" : "no") . "\n";