Search code examples
javascript16-bit8-bit

How to convert two 8-bits to 16-bits and vice versa in Javascript?


I know this has been asked before, but I have not been able to reach a solution. I apologize if the topic is duplicated, but I think it's not.

I have a number extracted from a Uint16Array to convert to a pair of 8-bit numbers and does it well, but when I want to convert from these two 8-bit numbers to the the first number I can't get it.

var firstNumber = 1118; // extracted from Uint16Array

var number8Bit1 = firstNumber & 0xff;
var number8Bit2 = ((firstNumber >> 8) & 0xff);

console.log(number8Bit1, number8Bit2); // 94, 4

var _firstNumber = (((number8Bit1 & 0xff) << 8) | (number8Bit2 & 0xff));

console.log(_firstNumber); // 24068 <-- 1118

You would be so kind as to help me please. Thank you.


Solution

  • You swapped the bytes:

    var _firstNumber = (((number8Bit2 & 0xff) << 8) | (number8Bit1 & 0xff));
    

    You have to do the reverse of the extraction when combining.

    var firstNumber = 1118; // extracted from Uint16Array
    
    var high = ((firstNumber >> 8) & 0xff);
    var low = firstNumber & 0xff;
    
    console.log(high, low); // 4, 94
    
    var _firstNumber = (((high & 0xff) << 8) | (low & 0xff));
    
    console.log(_firstNumber); // 1118