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 swap two bits of a 32-bit integer number in Java

1 Answer

0 votes
public class MyClass {
    private static int swap_bits(int  num, int pos1, int pos2) {
        int result = ((num & (1 << pos1)) >> pos1) ^ ((num & (1 << pos2)) >> pos2);
        
        if (result != 0) {
            num ^= (1 << pos1);
            num ^= (1 << pos2);
        }
        
        return num;
    }
    
    public static void main(String args[]) {
        int number = 41337; // 0000000000000000101000010-1-111-0-01
        int pos1 = 2;
        int pos2 = 6;
      
        System.out.println(String.format("%32s", Integer.toBinaryString(number)).replaceAll(" ", "0"));
     
        int swaped_bits = swap_bits(number, pos1, pos2);
     
        System.out.println(String.format("%32s", Integer.toBinaryString(swaped_bits)).replaceAll(" ", "0"));
    }
}





/*
run:
    
00000000000000001010000101111001
00000000000000001010000100111101
    
*/

 



answered Dec 22, 2023 by avibootz

Related questions

1 answer 113 views
1 answer 159 views
1 answer 112 views
1 answer 96 views
1 answer 111 views
1 answer 112 views
...