nodejs 數字 & buffer 間互轉

一、函數:十六進制轉buffer(如以字串型轉buffer將多耗一倍存儲空間)

function hextobin(bin, hex, len)
{//max wrote in 2018.4.26
	console.log('hex:',hex);
	var i;
	var upper_str = hex.toUpperCase();
	var dig;
	var base;
	
	//parseInt(j)
	for (i=0; i<len; i++) {
		if (upper_str.charCodeAt(i*2) >= 0x30 && upper_str.charCodeAt(i*2) <= 0x39)
			base = 0x30;
		else if (upper_str.charCodeAt(i*2) >= 0x41 && upper_str.charCodeAt(i*2) <= 0x5a)
			base = 0x41-10;
		else 
			base = 0;
		
		if (base != 0){
			bin[i] = (upper_str.charCodeAt(i*2)-base)<<4;
			//console.log('bin1 :',bin.toString('hex'));
			}
		else
			bin[i] = 0;
		
		if (upper_str.charCodeAt(i*2+1) >= 0x30 && upper_str.charCodeAt(i*2+1) <= 0x39)
			base = 0x30;
		else if (upper_str.charCodeAt(i*2+1) >= 0x41 && upper_str.charCodeAt(i*2+1) <= 0x5a)
			base = 0x41-10;
		else 
			base = 0;
		
		if (base != 0)
			bin[i] |= upper_str.charCodeAt(i*2+1)-base;
		//bin[i] = (((upper_str.charCodeAt(i*2)-65+10)<<4)|(upper_str.charCodeAt(i*2+1)-65+10));
	}
	
	console.log('bin.toString():',bin.toString('hex'));
	//console.log('bin.toString():',bin);
	//console.log("ori str", hex);
	return bin;
}

二、數字 & buffer 間互轉

var x=1234567899;     		         // 普通js變量,默認十進制
var x16= x.toString(16);	         //十進制轉十六進制(hex)
var bx16= Buffer.alloc(4);           //調用已寫好函數,將其轉為buffer
transToBinary.hextobin(bx16,x16,4);
console.log('bx16.length      :',bx16.length);
console.log('bx16             :',bx16);
console.log('bx16.toString hex:',bx16.toString('hex'));
var read=bx16.readUIntBE(0,4);       //採用無符號整形讀取buffer,其值即轉為十進制數字
console.log('readUIntBE       :',read);


猜你喜欢

转载自blog.csdn.net/lawrence_loh/article/details/80911297