How can negative numbers be handled when converting decimal to binary in PHP?
When converting negative numbers from decimal to binary in PHP, one common approach is to use the Two's Complement method. This involves flipping the bits of the positive binary representation of the number and then adding 1 to the result. This will give the correct binary representation of the negative number.
function decimalToBinary($num) {
if ($num >= 0) {
return decbin($num);
} else {
$positive_binary = decbin(abs($num));
$twos_complement = str_pad(str_replace('0', 'x', str_replace('1', '0', $positive_binary)), strlen($positive_binary), '1');
return $twos_complement;
}
}
// Example usage
$negative_num = -5;
echo decimalToBinary($negative_num); // Outputs: 11111111111111111111111111111011