//十进制buffer数组转八位二进制
function buffer2Bin(buffer, isReverse = false) {
let newBuffer = Buffer.from(buffer);
if (isReverse) {
newBuffer.reverse();
}
let bin = "";
for (let index = 0; index < newBuffer.length; index++) {
let dec = newBuffer[index];
bin += dec.toString(2).padStart(8, "0");
}
return bin;
}
//buffer转十六进制
//参数:buffer,是否转换为大写,转换前是否先以字节顺序原地交换
function buffer2HEX(buffer, isUpperCase = true, isReverse = false) {
let newBuffer = Buffer.from(buffer);
if (isReverse) {
newBuffer.swap16();
// newBuffer.reverse();
}
let hex = newBuffer.toString("hex");
if (isUpperCase) {
return hex.toUpperCase()
} else {
return hex;
}
}
//buffer转ASCII字符串
//参数:buffer,是否转换为大写,转换前是否先反转buffer
function buffer2ASSCIIByJs(buffer, isUpperCase = true, isReverse = false) {
let newBuffer = Buffer.from(buffer);
if (isReverse) {
newBuffer.reverse();
}
let ASSCII = "";
for (let index = 0; index < newBuffer.length; index++) {
let byte = newBuffer[index];
let ascii = String.fromCharCode(byte);
ASSCII += ascii;
}
if (isUpperCase) {
return ASSCII.toUpperCase()
} else {
return ASSCII;
}
}
//buffer转ASCII字符串
//参数:buffer,是否转换为大写,转换前是否先反转buffer
function buffer2ASSCIIByNode(buffer, isUpperCase = true, isReverse = false) {
var newBuffer = Buffer.from(buffer);
if (isReverse) {
newBuffer.reverse();
}
var ASSCII = newBuffer.toString("utf8");
if (isUpperCase) {
return ASSCII.toUpperCase()
} else {
return ASSCII;
}
}
//buffer转utf8字符串
//参数:buffer,转换前是否先反转buffer
function buffer2StringByNode(buffer, isReverse = false) {
let newBuffer = Buffer.from(buffer);
if (isReverse) {
newBuffer.reverse();
}
return newBuffer.toString("utf8");
}
//16进制字符串转10进制
function hex2int(hex) {
var len = hex.length, a = new Array(len), code;
for (var i = 0; i < len; i++) {
code = hex.charCodeAt(i);
if (48 <= code && code < 58) {
code -= 48;
} else {
code = (code & 0xdf) - 65 + 10;
}
a[i] = code;
}
return a.reduce(function (acc, c) {
acc = 16 * acc + c;
return acc;
}, 0);
}
//16进制字符串转2进制
function hex_to_bin(str) {
let hex_array = [{
key: 0,
val: "0000"
}, {
key: 1,
val: "0001"
}, {
key: 2,
val: "0010"
}, {
key: 3,
val: "0011"
}, {
key: 4,
val: "0100"
}, {
key: 5,
val: "0101"
}, {
key: 6,
val: "0110"
}, {
key: 7,
val: "0111"
},
{
key: 8,
val: "1000"
}, {
key: 9,
val: "1001"
}, {
key: 'a',
val: "1010"
}, {
key: 'b',
val: "1011"
}, {
key: 'c',
val: "1100"
}, {
key: 'd',
val: "1101"
}, {
key: 'e',
val: "1110"
}, {
key: 'f',
val: "1111"
}
]
let value = ""
for (let i = 0; i < str.length; i++) {
for (let j = 0; j < hex_array.length; j++) {
if (str.charAt(i).toLowerCase() == hex_array[j].key) {
value = value.concat(hex_array[j].val)
break
}
}
}
if (value.length < 8) {
for (let a = 0; a < value.length; a++) {
value = '0' + value
if (value.length == 8) {
return value
}
}
}
return value
}