Search code examples
javascriptbit-manipulationbitwise-operatorstyped-arrays

How to “rotate” the binary data (in horizontal direction) if its size is greater than 32 bits?


I have the following TypedArray (note that the size of this data is 80 bits):

var arr = new Uint8Array([10, 110, 206, 117, 200, 35, 99, 2, 98, 125]);

and I want to rotate it by N bits (where N is any integer from 0 to 79). For example, if N=50, I will represent it like this:

00001010 01101110 11001110 01110101 11001000 00100011 01100011 00000010 01100010 01111101
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

so the result should be

01101100 01100000 01001100 01001111 10100001 01001101 11011001 11001110 10111001 00000100
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

so arr[0] will be equal to 108, arr[1] will be equal to 96 etc. How to solve this?


Solution

  • To shift an entire byte-array bit-wise you can do:

    • First calculate how many bytes can be shifted (var bytes = (bits / 8)|0;)
    • Copy the number of bytes from one end, shift bytes over, paste previous slice in at the opposite end
    • Check if there is any bits remaining (var remainder = bits % 8)
    • If any remainder (!=0) left then loop through, copy and shift previous byte the number of bits in opposite direction and 8-remainding bits (var prev = arr[arr.length - 1] << (8- remainder);) (see demo for details).
    • Shift byte over and merge with previous shifted byte (arr[i] = (arr[i]>>>remainder) | prev;)

    Demo

    // main rotation function
    function rotate(arr, bits) {
    
      var arrBits = arr.length<<3;
      var aBits = Math.abs(bits) % arrBits;       // "clamp" and make positive value
      aBits = bits < 0 ? arrBits - aBits : aBits; // direction
    
      var bytes = (aBits / 8)|0;       // how many bytes we can pre-rotate
      var remainder = aBits % 8;       // number of additional bits that needs to rotate
      var iRemainder = 8 - remainder;  // inverse (cached for convenience)
      var first;                       // first shift added to end
    
      // first rotate based on number of whole bytes, get slice of end
      var rBytes = arr.slice(arr.length - bytes);
       
      // shift over remainding array byte-wise
      arr.copyWithin(bytes, 0);
       
      // set previous slice from end to beginning
      arr.set(rBytes);
       
      // shift remainders, if any (>0)
      if (remainder) {
        first = (arr[arr.length - 1] << iRemainder);    // need this at the end
    	
        for(var i = arr.length-1; i > 0; i--) {         // iterate in reverse
          var prev = (arr[i - 1] << iRemainder);        // get previous byte shifted
          arr[i] = (arr[i]>>>remainder) | prev;         // shift current, merge w/prev
        }
        arr[0] = (arr[0]>>>remainder) | first           // shift last and merge w/first
      }
    }
    
    // DEMO STUFF -
    var rng = document.getElementById("bits");
    var cnt = document.getElementById("cnt");
    var out = document.getElementById("out");
    function toBin(arr) {
      for(var i=0, str="", str2=""; i < arr.length; i++) {
        str+= pad(arr[i]) + " ";
        str2 += arr[i].toString() + " ";
      }
      return str.replace(/0/g, "<span class=c>0</span>") + "<br>" + str2;
    }
    function pad(b) {
      var s = "00000000" + b.toString(2);
      return s.substr(s.length - 8)
    }
    function update() {
      var arr = new Uint8Array([10, 110, 206, 117, 200, 35, 99, 2, 98, 125]);
      cnt.innerHTML = rng.value;  rotate(arr, +rng.value); out.innerHTML = toBin(arr)
    }
    update(); rng.oninput = update;
    body {font:16px sans-serif;margin-left:0}
    #out {font:12px monospace;white-space:nowrap}
    .c {color:#999} div {margin-top:10px}
    <label>Bits: <input id=bits type=range min=-80 max=80 value=0></label> <span id=cnt>0</span>
    <div id=out></div>

    To rotate the opposite direction simply subtract number of bits from total number of bits (arrayByteLength x 8 - bits), just remember to apply modulo on the result based on array length.