Swap even and odd bits of unsigned 8-bit integer The task:


  Given an unsigned 8-bit integer, swap its even and odd bits. The 1st
  and 2nd bit should be swapped, the 3rd and 4th bit should be swapped,
  and so on.
  
  For example, 10101010 should be 01010101. 11100010 should be 11010001.
  
  Bonus: Can you do this in one line?


My solutions:

// imperative:
function swap8BitInteger(bytes){
  let copiedBytes = '';
  for(let i = 0; i &lt; bytes.length; i+=2) {
    copiedBytes+= `${bytes[i+1]}${bytes[i]}`;
  }
  return copiedBytes;
}

console.log(swap8BitInteger('11100010'));

// I don't know wether this qualifies as a one-liner
const swap8BitInteger2 = bytes =&gt; bytes.split('').reduce((acc, bit, idx) =&gt; {acc[idx % 2 === 0 ? idx + 1 : idx - 1] = bit;return acc;}, []).join('');

console.log(swap8BitInteger2('11100010'));

// Not sure wether this is still readable
const swap8BitInteger3 = bytes =&gt; bytes.split('').reduce((acc, _, idx) =&gt; idx % 2 ? acc : acc + bytes[idx + 1] + bytes[idx], '');

console.log(swap8BitInteger3('11100010'));


Would be interested to see an even shorter (and/or more readable) solution.
OMDG arrays to manipulate bits
Bit manipulation is the most basic type of operation a computer can do. These days it can mess with 64 bit in one go. JS number (as signed int 32) is limited to 32 (to keep us in our place)
BTW JS has 8, 16, 32bit signed and unsigned arrays.
In JS you can write binary numbers with the 0b prefix. Eg 0b111 is 7
To swap even odd, you shift all bits to the left &lt;&lt; 1 (same as * 2) and mask out &amp; 0b10101010 the odd bits. The for the even you shift all bits to the right &gt;&gt; 1 similar to /2, mask out the even bits &amp; 0b101010101 and add or or the result of the previous shift.
Example show two ways of doing the same thing.


const swapEvenOdd = char =&gt; ((char &lt;&lt; 1) &amp; 0b10101010) | ((char &gt;&gt; 1) &amp; 0b1010101);

const swapEvenOdd2 = char =&gt; ((char * 2) &amp; 170) + ((char / 2) &amp; 85);


console.log(swapEvenOdd(0b01100110).toString(2).padStart(8,"0"))
console.log(swapEvenOdd2(0b01100110).toString(2).padStart(8,"0"))