Skip to content

Instantly share code, notes, and snippets.

@fundon
Created June 20, 2011 06:59
Show Gist options
  • Save fundon/1035236 to your computer and use it in GitHub Desktop.
Save fundon/1035236 to your computer and use it in GitHub Desktop.
What can you do with bytes?
// notes: http://jsperf.com/transloc-getters
// http://www.bytearray.org/?p=711
// testing in Nodejs console
function Bits() {
this._buffer = 0;
this._length = 0;
// 写入时虚拟指针
this._wpointer = 0;
// 读出时虚拟指针
this._rpointer = 0;
}
Bits.prototype = {
write: function(bit) {
if ( 1 < bit || 0 > bit ) {
throw new Error('只能输入0或者1.');
}
// 从右开始写入
return this._buffer |= (bit << (this._length = this._wpointer++));
},
read: function() {
if (this._rpointer > this._length) {
throw new Error('目标读取位置超出元组的长度')
}
//return this._buffer & (1 << this._rpointer++);
// 从右开始读出
return +((this._buffer & (1 << this._rpointer++)) >> (this._rpointer - 1) != 0);
},
get buffer() {
return this._buffer;
},
get rpointer() {
return this._rpointer;
},
get wpointer() {
return this._wpointer;
},
set rpointer(r) {
this._rpointer = r;
},
set wpointer(w) {
this._wpointer = w;
}
};
var b = new Bits();
console.log(b.write(1).toString(2));
console.log(b.write(0).toString(2));
console.log(b.write(1).toString(2));
console.log(b.write(1).toString(2));
console.log(b.read());
console.log(b.read());
b.rpointer = 2;
console.log(b.read());
console.log(b.read())
console.log(b.rpointer);
console.log(b.wpointer);
console.log(b.buffer);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment