2015-01-06 49 views

回答

4

在節點中,我們可以利用緩衝區從十六進制字符串中抓取整數。

.findOne(cond, function(err, doc){ 
    // create a 12 byte buffer by parsing the id 
    var ctr = 0; 
    var b = new Buffer(doc._id.str, 'hex'); 

    // read first 4 bytes as an integer 
    var epoch = b.readUInt32BE(0); 
    ctr += 4; 

    // node doesn't have a utility for 'read 3 bytes' so hack it 
    var machine = new Buffer([0, b[ctr], b[ctr+1], b[ctr+2]]).readUInt32BE(0); 
    ctr += 3; 

    // read the 2 byte process 
    var process = b.readUInt16BE(ctr); 
    ctr += 2; 

    // another 3 byte one 
    var counter = new Buffer([0, b[ctr], b[ctr+1], b[ctr+2]]).readUInt32BE(0); 
}); 

對於驅動程序版本< 2.2變化到doc._id.strdoc._id.toHexString()

可能更簡單的技術就是使用parseInt和slice。因爲十六進制數字是一個字節的一半,所以我們的偏移量是兩倍高。

var id = doc._id.str, ctr = 0; 
var epoch = parseInt(id.slice(ctr, (ctr+=8)), 16); 
var machine = parseInt(id.slice(ctr, (ctr+=6)), 16); 
var process = parseInt(id.slice(ctr, (ctr+=4)), 16); 
var counter = parseInt(id.slice(ctr, (ctr+=6)), 16);