Reputation: 1550
Background
I'm using Three.JS
to create a heightmap viewer.
The data of the height-points of the height-map are UInt16
, meaning they are two bytes.
I save the two bytes as R
and G
values in pixels of a PNG
file and then send the picture to my Three.JS
height-map viewer and manipulate the vertices Y
position of a PlaneGeometry
.
Problem
I can't figure out how to combine the two bytes together to a Javascript number.
Here's some code that doesn't seem to do what I need:
var result = (((byteA[0] & 0xFF) << 8) | (byteB[1] & 0xFF));
Question
How do I turn two bytes into one number in Javascript?
Upvotes: 2
Views: 1904
Reputation: 15881
"How do I turn two bytes into one number in Javascript?"
Here's a quick working example code to combine two byte values into one result:
<!DOCTYPE html>
<html>
<body>
<script>
var bytes = new Uint8Array(2); <!-- length for 2 items -->
bytes[0] = 0xAA;
bytes[1] = 0xBB;
var result = ( ( (bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF) );
alert("combined bytes have value : " + result);
</script>
</body>
</html>
Gives correct result of (hex 0xAABB
= decimal 43707
) :
combined bytes have value : 43707
If you want two separate bytearrays bytesA and bytesB then you'll have to create two separate Uint8Array
(of total items/entries length) then fill each one with your values. Combine as usual.
There is also option to create Uint16Array
if you later need to store result
value in some bytes also (ie: not just as number). PS : You can read some useful info about Typed Arrays here.
Upvotes: 4