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 Java

1 Answer

0 votes
public class MyClass {
    private static void print_bits(int n) {
    	System.out.println(String.format("%32s", Integer.toBinaryString(n)).replaceAll(" ", "0"));
    }
    
    private static int reverseBits(int num) {
    	int total_bits = (Integer.SIZE / Byte.SIZE) * 8;
    	int reversed_bits = 0;
    
    	for (int i = 0; i < total_bits; i++) {
    		if ((num & (1 << i)) != 0) {
    			reversed_bits |= 1 << ((total_bits - 1) - i);
    		}
    	}
    
    	return reversed_bits;
    }
    
    public static void main(String args[]) {
	    int num = 42;
	    print_bits(num);
	    num = reverseBits(num);
	    print_bits(num);
	    
	    System.out.println();

	    num = 19;
	    print_bits(num);
	    num = reverseBits(num);
	    print_bits(num);
    }
}






/*
run:
  
00000000000000000000000000101010
01010100000000000000000000000000

00000000000000000000000000010011
11001000000000000000000000000000
  
*/

 



answered Dec 20, 2023 by avibootz
edited Dec 20, 2023 by avibootz

Related questions

1 answer 169 views
1 answer 107 views
1 answer 102 views
1 answer 97 views
1 answer 108 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
...