Home > Enterprise >  PHP flip 32bit integer
PHP flip 32bit integer

Time:11-22

get 32 bit unsigned integer. Flip all the bits (0->1 and 1->0 ) and return the result as an unsigned integer.

Take 1 for example, as unsigned 32-bits is 00000000000000000000000000000001 and doing the flipping we get 11111111111111111111111111111110 which in turn is 4294967294.

I can turn decimal number to binary , but it does not contain 32 bits to flip. Please help me with this.

CodePudding user response:

This is very much a basics of programming issue; and anyone that posts code that is using string handling is very much not someone you want to learn from.

That said, pack() is an excellent function; but doesn't help with understanding exactly what is happening.

To invert a 32 bit value; let's think about an int in PHP. First off int's are 64 bits; but that's okay; we can use masks as well, to ensure we get the expected answer (even if PHP changes the default int width).

$value = some_int_value; // the value to invert
$value = !$value; // flip all 64 bits
$value = $value & 0xffffffff; // ignore anything but the last 32 bits

Or more succinctly

$invert_32_unsigned = 0xffffffff & !intval($value);

CodePudding user response:

For PHP, you may use decbin and bindec for decimal to binary and binary to decimal respectively, and use a simple function to invert the bits.

I have made a function xinvert to do the job, as follows:

<?php

$value1=1;
echo xinvert($value1) ."<br>";

$value1=10;
echo xinvert($value1) ."<br>";


function xinvert($value1)
{
$string1= sprintf( "2d",decbin($value1));

$index=0;
$string2="";
  while ($index < strlen($string1) ) {
   if (substr($string1, $index,1)=="0"){
     $string2.="1";
      }else{
     $string2.="0";
    }
  $index  ;
  }
return bindec($string2);
}

?>

Note: I have used sprintf( "2d",decbin($value1)); to make it 32 bit in length.

See the sandbox result as follows:

http://sandbox.onlinephpfunctions.com/code/140edad989ca5101f1888bf8a9e03b484166c83e

CodePudding user response:

This is basics of programming, PHP has a full support of bitwise operators, including bitwise NOT:

$result = unpack('V', ~pack('V', 1234))

Pack and unpack are used here to deal with a fact that all integers in PHP are signed 64 bits integers. Don't listen to people that are converting 4-byte numbers into strings or array of strings, they have no clue what they do.

CodePudding user response:

This can be achieved with a single binary operation: the XOR

echo $v ^ 0xffffffff;

CodePudding user response:

I did it thanx everyone. This is how I did.

$function flippingBits($n) { 
    $binary = sprintf('2b', $n);
    $fliped = strtr($binary, [1,0]);
    return bindec($fliped);
}
  • Related