problem: in video-games there are tons of low precision numbers that can be packed together over the network to dramatically save bandwidth compared to sending strings. Strings are allocated to UTF-8 which uses 1 byte for each character.
Ideally there should be a way to write these numbers together:
- player id in game- precision 0-1023 range, 10 bits
- player rotation- quaternion- a few numbers ending up as 24 bits after some math simplification
- player inputs- 0-1 range x2, 2 bits
How do you take low precision numbers like this and put them in a array buffer / blob?
You can use a
Uint32Array
, and then use bit shift and mask operations to store values in that array.For example, if you wanted to store a 4 bit number, and then a 10 bit number (leaving 18 bits left over for more fields):
and to extract those fields:
The array can be accessed as an
ArrayBuffer
for serialisation by accessing its.buffer
property.