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.

39,987 questions

51,931 answers

573 users

How to reverse the bits of a number in Python

1 Answer

0 votes
def reverse_bits(num):
    total_bits = 32
    reverse_bits = 0
    
    for i in range(total_bits):
        if (num & (1 << i)):
            reverse_bits |= 1 << ((total_bits - 1) - i)
    
    return reverse_bits
 
num = 42
print('{:032b}'.format(num))
num = reverse_bits(num)
print('{:032b}'.format(num) + '\n')

num = 19
print('{:032b}'.format(num))
num = reverse_bits(num)
print('{:032b}'.format(num))




'''
run:

00000000000000000000000000101010
01010100000000000000000000000000

00000000000000000000000000010011
11001000000000000000000000000000
 
'''

 



answered Dec 13, 2023 by avibootz

Related questions

1 answer 126 views
1 answer 107 views
1 answer 101 views
1 answer 96 views
1 answer 100 views
100 views asked Dec 13, 2023 by avibootz
1 answer 123 views
123 views asked Dec 12, 2023 by avibootz
2 answers 169 views
...