Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

350
Views
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.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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);
over 4 years ago · Santiago Trujillo Report

0

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);
}
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!