问题:在电子游戏中,有大量的低精度数字可以通过网络打包在一起,与发送字符串相比,大大节省了带宽。字符串分配给UTF-8,它对每个字符使用一个字节.
理想情况下,应该有一种将这些数字写在一起的方法:
如何将这样的低精度数字放在数组缓冲区/ blob中?
发布于 2016-12-28 09:23:47
您可以使用Uint32Array,然后使用位移位和掩码操作将值存储在该数组中。
例如,如果您想存储一个4位数字,然后存储一个10位数字(留下18位用于更多字段):
array[0] = (num0 & 0x0f) << 0) |
(num1 & 0x3ff) << 4);并提取这些字段:
num0 = (array[0] >>> 0) & 0x0f;
num1 = (array[0] >>> 4) & 0x3ff;通过访问数组的ArrayBuffer属性,可以将数组作为序列化的.buffer访问。
发布于 2016-12-29 05:21:17
根据Alnitak的答复:
function binPush(arr, i, num, max) {
arr[i] = arr[i] << max.toString(2).length; //shift int32 $max (in base 2) bits to the left to allow for allocation
arr[i] |= num; // OR bitwise operation, which copies the 1s from $num
}
var myArr = new Uint32Array(1);
binPush(myArr, 0, 3, 3); // push 11: 00000000000000000000000000000011
binPush(myArr, 0, 10, 15); // push 1010: 00000000000000000000000000111010
binPush(myArr, 0, 120, 127); // push 1111000: 00000000000000000001110101111000
binPush(myArr, 0, 120, 255); // push 01111000: 00000000000111010111100001111000注意,最后一个binPush是如何将一个额外的0添加到前面的,因为最大值是255,这正好是8位,而120是7位。
发布于 2016-12-28 09:33:51
在这里,也许MathewBarker的位流会有所帮助。
https://stackoverflow.com/questions/41358190
复制相似问题