Last active
April 5, 2021 18:56
-
-
Save arseniyturin/acf61714284837b41661e7509724384a to your computer and use it in GitHub Desktop.
How to convert two 8bit number into 16bit in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Problem: | |
You have 16 bit number, for example 12345. | |
In hexadecimal it looks like this: 0x3039, | |
but in the buffer it will look like this: <Buffer: 39 30> | |
How to convert two 8 bit numbers back to 16 bit number? | |
Bitwise operator '<<' | |
*/ | |
/* ----- Code ----- */ | |
let buffer = message.binaryData; // <Buffer: 39 30> | |
let number = (buffer[1] << 8) + buffer[0]; // 12345 | |
/* | |
Explanation: | |
Node buffer stores binary data in bytes (8 bit) in `Little Endian` order, | |
in simple words your hex number will be reversed in order (0x3039 became [0x39, 0x30]) | |
To put two 8 bit numbers together we need bitwise operator '<<', | |
which works similar to string concatenation ('abc' + '123' => 'abc123'), | |
but because we're dealing with numbers we can't simply sum them up. | |
So, we take second element it the buffer, shift it 8 bits to the left (30 => 30__) | |
and add first element to it (30__ => 3039) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment