Node.js的Buffer
非常不错。但是,它似乎更适合存储字符串。构造函数可以接受一个字符串、一个字节数组或要分配的字节数。
我正在使用Node.js 0.4.12版本,想在缓冲区中存储一个整数。不是integer.toString()
,而是整数的实际字节。有没有一种简单的方法可以做到这一点,而无需循环整数并进行一些位操作?我可以这样做,但我觉得这是其他人可能曾经面对过的问题。
var buf = new Buffer(4);
buf.writeUInt8(0x3, 0);
http://nodejs.org/docs/v0.6.0/api/buffers.html#buffer.writeUInt8
使用较新版本的Node更加容易。以下是一个2字节无符号整数的示例:
let buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(1234); // Big endian
或者对于一个4字节的有符号整数:
let buf = Buffer.allocUnsafe(4); // Init buffer without writing all data to zeros
buf.writeInt32LE(-123456); // Little endian this time..
不同的 writeInt
函数是在 Node v0.5.5 中添加的。
查看这些文档以获得更好的理解:
Buffer
writeUInt16BE/LE
writeUIntBE/LE
allocUnsafe
由于在0.4.12中没有内置此功能,您可以尝试使用以下类似方法:
var integer = 1000;
var length = Math.ceil((Math.log(integer)/Math.log(2))/8); // How much byte to store integer in the buffer
var buffer = new Buffer(length);
var arr = []; // Use to create the binary representation of the integer
while (integer > 0) {
var temp = integer % 2;
arr.push(temp);
integer = Math.floor(integer/2);
}
console.log(arr);
var counter = 0;
var total = 0;
for (var i = 0,j = arr.length; i < j; i++) {
if (counter % 8 == 0 && counter > 0) { // Do we have a byte full ?
buffer[length - 1] = total;
total = 0;
counter = 0;
length--;
}
if (arr[i] == 1) { // bit is set
total += Math.pow(2, counter);
}
counter++;
}
buffer[0] = total;
console.log(buffer);
/* OUTPUT :
racar $ node test_node2.js
[ 0, 0, 0, 1, 0, 1, 1, 1, 1, 1 ]
<Buffer 03 e8>
*/
// Filled 8 bits number
const fillByte = 0xff;
function bufferFromInt(num){
const buffArr = [];
do {
buffArr.push(fillByte & num);
} while(num >>= 8);
return Buffer.from(buffArr.reverse())
}