Hashan
Hashan

Reputation: 158

PHP flip 32bit integer

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.

Upvotes: 2

Views: 749

Answers (5)

Ken Lee
Ken Lee

Reputation: 8063

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=10;
echo xinvert($value1) ."<br>";

function xinvert($value1){
$string1= sprintf( "%032d",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( "%032d",decbin($value1)); to make it 32 bit in length, which is inspired by user3783243

Upvotes: 0

Hashan
Hashan

Reputation: 158

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

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

Upvotes: 2

Daniels118
Daniels118

Reputation: 1227

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

echo $v ^ 0xffffffff;

Upvotes: 0

haxbits
haxbits

Reputation: 27

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);

Upvotes: 0

user1597430
user1597430

Reputation: 1146

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.

Upvotes: -1

Related Questions