创建一个大位字段?

创建一个大位字段?

问题描述:

我想在JavaScript中创建一个大位字段,它将有效地表示多维标记数组(使用索引来跳转到物理1D结构中的各个维度)。

I want to create a large bit field in JavaScript that will effectively represent a multi-dimensional array of markers (uses indexing to jump to various dimensions in the physical "1D" structure).

我正在考虑如何使用字符串作为位,而不是一堆数字,所以我可以先分配一个适当长度的字符串。数据类型,Unicode和转换等注意事项发挥作用(在JavaScript 1.3之前也没有Unicode支持)。

Rather than a bunch of numbers, I'm considering how I might use a string as bits, so I can allocate a string of the appropriate length first. Considerations such as data types, Unicode and conversions come into play (also no Unicode support before JavaScript 1.3).

然而,我对其他建议如何使用JavaScript来实现大比特字段持开放态度。

However I'm open about other suggestions how to use JavaScript to achieve a large bit field.

更新:

仅供参考:平均而言,我可能会使用~2187位/标记(274字节) ),但想要一个通用的答案,而不是可以容纳更多的位。

Update:
Just for informational purposes: On average I might be using ~2187 bits/markers (274 bytes), but would like a generic answer than can accommodate many more bits.

字符串的一个问题是它们是不可变的,因此,如果你想改变任何东西,你需要重建字符串。

One problem with strings is that they are immutable, so if you want to change anything, you would need to rebuild the string.

我会坚持使用数字。使用按位运算符,每个数字可以匹配32位。

I would just stick to using numbers. Using the bitwise operators, you can fit 32 bits in each number.

最多可以容纳53位,因为JavaScript数字是双精度浮点数,但是按位运算符将其操作数转换为32位整数,因此您无法使用它们来获取单个位(如果您愿意,可以使用除法组合完成相同的操作, Math .pow 等,但会更复杂。)

You could fit up to 53 bits, since JavaScript numbers are double-precision floating point, but the bitwise operators convert their operands to 32-bit integers, so you wouldn't be able to use them to get at the individual bits (if you wanted to, you could accomplish the same thing with combinations of division, Math.pow, etc. but it would be more complicated).

这是一个基本的实现,可以让你获取,设置和取消设置各个位:

Here's a basic implementation that lets you get, set, and unset individual bits:

function BitField() {
    this.values = []; // You could set the length here, but it's not necessary
}

BitField.prototype.get = function(i) {
    var index = (i / 32) | 0; // | 0 converts to an int. Math.floor works too.
    var bit = i % 32;
    return (this.values[index] & (1 << bit)) !== 0;
};

BitField.prototype.set = function(i) {
    var index = (i / 32) | 0;
    var bit = i % 32;
    this.values[index] |= 1 << bit;
};

BitField.prototype.unset = function(i) {
    var index = (i / 32) | 0;
    var bit = i % 32;
    this.values[index] &= ~(1 << bit);
};