2

I have a binary number 11000 i need to flip the number to get the answer 00111 and i need the result in PHP, i did it using the for loop but how can i do it using bitwise operator i think we can do it using ^ operator here is the PHP solution:

function getIntegerComplement($n) {
    // $n is a decimal number
    $binary = decbin($n);
    $arr = str_split($binary);  

    $complement = "";
    foreach($arr as $i)
      $complement .= ($i == 0) ? (1) : (0);
}

any help would be appriciated

Wasif Khalil
  • 2,217
  • 9
  • 33
  • 58

3 Answers3

3

If you negate the whole int, you'll get a negative number: as int consists of 32 bits (usually), and all of them will be negated. And when the 1-st bit becomes 1, php will treat it as a negative number. And you want to negate only last 5 bits. Here it is done, using the $val + $mask (mod 2):

<?php
$val = bindec('11000');
$mask = bindec('11111');
$val = $val ^ $mask;

print sprintf('%05d', decbin($val));

Prints 00111, just as expected.

user4035
  • 22,508
  • 11
  • 59
  • 94
2

Use the bitwise NOT operator:

return ~$n;
nickb
  • 59,313
  • 13
  • 108
  • 143
0

Use "NOT" ( ~ ). It reverses the supplied value:

function getIntegerComplement($n) {
return ~$n;
}

More info here: http://php.net/manual/en/language.operators.bitwise.php

~ $a ---> Not: Bits that are set in $a are not set, and vice versa.

pudelhund
  • 512
  • 2
  • 4
  • 16
  • not getting the exact result for binary numbers $n is a decimal num – Wasif Khalil Jul 24 '13 at 13:18
  • you put in a 0, result is 1. i do not quite understand what else you wnat to achieve... just run decbin($n) on your decimal number and you get the binary result which you may now reverse using the NOT operator – pudelhund Jul 24 '13 at 13:54
  • i want to achieve this: = Take a decimal number = convert it to binary = convert 0 to 1 and 1 to 0 = convert that binary to decimal = echo that decimal – Wasif Khalil Jul 24 '13 at 14:09
  • function getIntegerComplement2($n) { echo "this is the num: ".$n; echo "
    "; $binary = decbin($n); echo "this is binary: " . $binary; echo "
    "; echo "Flipped the binary numbers? ". ~$binary; }
    – Wasif Khalil Jul 24 '13 at 14:16
  • above code has this result: this is the num: 50 this is binary: 110010 Flipped the binary numbers? ÎÎÏÏÎÏ – Wasif Khalil Jul 24 '13 at 14:17