forked from lmclupr/brickpi-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitArray.js
More file actions
51 lines (37 loc) · 1.16 KB
/
Copy pathBitArray.js
File metadata and controls
51 lines (37 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
var BitArray = function(array) {
this._array = Array.isArray(array) || Buffer.isBuffer(array) ? array : []
this._bitOffset = 0
}
BitArray.prototype.addBits = function(byteOffset, bitOffset, bits, value) {
for(var i = 0; i < bits; i++) {
var index = byteOffset + Math.floor((bitOffset + this._bitOffset + i) / 8)
if(this._array.length < index) {
for(var n = this._array.length; n < index; n++) {
this._array.push(0)
}
}
if(this._array[index] === undefined) {
this._array[index] = 0
}
if(value & 0x01) {
this._array[index] |= (0x01 << ((bitOffset + this._bitOffset + i) % 8))
}
value = value >> 1
}
this._bitOffset += bits
}
BitArray.prototype.getBits = function(byteOffset, bitOffset, bits) {
var result = 0
for(var i = bits; i > 0; i--) {
var index = byteOffset + Math.floor((bitOffset + this._bitOffset + (i - 1)) / 8)
var position = (bitOffset + this._bitOffset + (i - 1)) % 8
result *= 2
result |= (this._array[index] >> position) & 0x01
}
this._bitOffset += bits
return result
}
BitArray.prototype.getArray = function() {
return this._array
}
module.exports = BitArray