Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

354
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda