How can PHP be used for binary calculations?
PHP can be used for binary calculations by utilizing the built-in functions for binary operations such as bindec() for converting binary to decimal and decbin() for converting decimal to binary. Additionally, bitwise operators like & (AND), | (OR), ^ (XOR), and ~ (NOT) can be used to perform binary calculations in PHP.
// Convert binary to decimal
$binaryNumber = '1010';
$decimalNumber = bindec($binaryNumber);
echo "Binary $binaryNumber is equal to decimal $decimalNumber";
// Convert decimal to binary
$decimalNumber = 10;
$binaryNumber = decbin($decimalNumber);
echo "Decimal $decimalNumber is equal to binary $binaryNumber";
// Perform bitwise operations
$num1 = 5; // binary 101
$num2 = 3; // binary 011
$resultAnd = $num1 & $num2; // bitwise AND
$resultOr = $num1 | $num2; // bitwise OR
$resultXor = $num1 ^ $num2; // bitwise XOR
$resultNot = ~$num1; // bitwise NOT
echo "AND: $resultAnd, OR: $resultOr, XOR: $resultXor, NOT: $resultNot";