© Parineeth M R

** Question 33. Given an integer, swap the bit at position 1 with the bit at position 2**

We first extract the bits at position 1 and position 2. We then have to swap the two bits only if the two bits are different. The code for swapping the bits is given below

## C/C++

/* x: integer in which the bits should be swapped pos1: position of first bit to be swapped pos2: position of the second bit to be swapped */ unsigned int swap_bits(unsigned int x, int pos1, int pos2) { /*get the bits at position pos1 and pos2*/ int bit1 = (x >> pos1) & 1; int bit2 = (x >> pos2) & 1; /*swap the bits if the bits are different*/ if (bit1 != bit2) { x = write_bit(x, bit1, pos2); x = write_bit(x, bit2, pos1); } return x; } /*writes the bit_value (0/1) into position pos in x and returns the result*/ unsigned int write_bit(unsigned int x, int bit_value, int pos) { unsigned int mask = 1 << pos; if (bit_value) x = x | mask; else x = x & ~mask; return x; }

## Java

/* x: integer in which the bits should be swapped pos1: position of first bit to be swapped pos2: position of the second bit to be swapped */ public static int swapBits(int x, int pos1, int pos2) { /*get the bits at position pos1 and pos2*/ int bit1 = (x >> pos1) & 1; int bit2 = (x >> pos2) & 1; /*swap the bits*/ if (bit1 != bit2) { x = writeBit(x, bit1, pos2); x = writeBit(x, bit2, pos1); } return x; } /*writes the bitValue (0/1) into position pos in x and returns the result*/ public static int writeBit( int x, int bitValue, int pos) { int mask = 1 << pos; if (bitValue == 1) x = x | mask; else x = x & ~mask; return x; }

## Python

#writes the bit_value (0/1) into position pos in x and returns the result def write_bit(x, bit_value, pos): mask = 1 << pos if (bit_value == 1): x = x | mask else: x = x & ~mask return x #x: integer in which the bits should be swapped #pos1: position of first bit to be swapped #pos2: position of the second bit to be swapped def swap_bits(x, pos1, pos2): #get the bits at position pos1 and pos2 bit1 = (x >> pos1) & 1 bit2 = (x >> pos2) & 1 #swap the bits if (bit1 != bit2) : x = write_bit(x, bit1, pos2) x = write_bit(x, bit2, pos1) return x