nodejs Buffer非常膨胀.但是,它似乎是为了存储字符串.构造函数要么采用字符串,字节数组,要么分配大小的字节.
我使用的是Node.js的0.4.12版本,我想在缓冲区中存储一个整数.不是integer.toString(),但整数的实际字节.有没有一种简单的方法可以做到这一点,而不需要遍历整数并进行一些小问题?我能做到这一点,但我觉得这是别人在某个时候必须面对的问题.
Chr*_*rdi 35
var buf = new Buffer(4);
buf.writeUInt8(0x3, 0);
Run Code Online (Sandbox Code Playgroud)
http://nodejs.org/docs/v0.6.0/api/buffers.html#buffer.writeUInt8
使用更新版本的 Node,这要容易得多。下面是一个 2 字节无符号整数的例子:
let buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(1234); // Big endian
Run Code Online (Sandbox Code Playgroud)
或者对于 4 字节有符号整数:
let buf = Buffer.allocUnsafe(4); // Init buffer without writing all data to zeros
buf.writeInt32LE(-123456); // Little endian this time..
Run Code Online (Sandbox Code Playgroud)
writeInt节点 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>
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29282 次 |
| 最近记录: |