Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

351
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda