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

1

6

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.

Micrometeorite answered 18/4, 2015 at 4:38 Comment(0)
C
7

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
Careen answered 18/4, 2015 at 4:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.