How to swap all odd and even bits in JavaScript

1 Answer

0 votes
/**
 * Swaps odd and even bits in a 32-bit unsigned integer.
 * For example, bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, etc.
 */
function swapsOddAndEvenBits(n) {
  // Mask to isolate odd bits: binary 101010... (hex: 0xAAAAAAAA)
  const oddBits = n & 0xAAAAAAAA;

  // Mask to isolate even bits: binary 010101... (hex: 0x55555555)
  const evenBits = n & 0x55555555;

  console.log(`oddBits: ${toBitString(oddBits, 8)}`);
  console.log(`evenBits: ${toBitString(evenBits, 8)}`);

  // Shift odd bits right to move them to even positions
  const shiftedOddBits = oddBits >>> 1;

  // Shift even bits left to move them to odd positions
  const shiftedEvenBits = evenBits << 1;

  console.log(`oddBits Right-shift: ${toBitString(shiftedOddBits, 8)}`);
  console.log(`evenBits Left-shift: ${toBitString(shiftedEvenBits, 8)}`);

  // Combine the shifted bits
  return shiftedOddBits | shiftedEvenBits;
}

/**
 * Converts a number to a binary string with fixed width.
 * Pads with leading zeros to match the desired bit width.
 */
function toBitString(n, width) {
  return (n >>> 0).toString(2).padStart(width, '0').slice(-width);
}


const n = 90;

console.log(`Input: ${toBitString(n, 8)}`);

const result = swapsOddAndEvenBits(n);

console.log(`Result: ${toBitString(result, 8)}`);



/*
run:
 
Input: 01011010
oddBits: 00001010
evenBits: 01010000
oddBits Right-shift: 00000101
evenBits Left-shift: 10100000
Result: 10100101
 
*/

 



answered Oct 26, 2025 by avibootz
edited Oct 26, 2025 by avibootz
...