Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to print the bits of a number in PHP

3 Answers

0 votes
function print_bits($n) {
    for ($i = 31; $i >= 0; $i--) {
        echo ($n >> $i) & 1;
    }
    echo "<br />";
}

$n = 1358;

print_bits($n);



/*
run:
     
00000000000000000000010101001110
    
*/

 



answered Mar 6, 2019 by avibootz
0 votes
echo decbin(3) . "\n";
 
echo decbin(10) . "\n"; 
 
echo decbin(15) . "\n"; 
 
echo decbin(180) . "\n"; 
 
echo decbin(255); 
 
 
 
  
/*
run:
  
11
1010
1111
10110100
11111111
  
*/

 



answered Mar 6, 2019 by avibootz
edited Apr 19, 2024 by avibootz
0 votes
function get_bits($n, $len = 8) {
    return str_pad(decbin($n), $len, "0", STR_PAD_LEFT);
}
      
      
echo get_bits(3) . "\n";
  
echo get_bits(10) . "\n"; 
  
echo get_bits(15) . "\n"; 
  
echo get_bits(180) . "\n"; 
  
echo get_bits(255); 
  
  
  
/*
run:
 
00000011
00001010
00001111
10110100
11111111
 
*/

 



answered Apr 19, 2024 by avibootz
edited Jan 29, 2025 by avibootz

Related questions

...