一、十六进制转字符串
c
export const hexToStr = function(hex, encoding) {
var trimedStr = hex.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
var curCharCode;
var resultStr = [];
for (var i = 0; i < len; i = i + 2) {
curCharCode = parseInt(rawStr.substr(i, 2), 16);
resultStr.push(curCharCode);
}
var val = "";
var arr = resultStr;
for (let i = 0; i < arr.length; i++) {
val += String.fromCharCode(arr[i]);
}
return val;
}
二、十进制转16进制
c
export const tenToHex = (num, digit = 4) => {
const hex = num.toString(16);
return hex.padStart(digit, 0);
}
三、字符串转16进制
c
export const stringToHex = (str) =>{
var val = "";
for (var i = 0; i < str.length; i++) {
if (val == "") {
val = str.charCodeAt(i).toString(16); //获取字符的Unicode码然后转16进制
} else {
val += str.charCodeAt(i).toString(16); //获取字符的Unicode码然后转16进制再拼接,中间用逗号隔开
}
}
return val;
}
四、arrayBuffer转16进制字符串
c
export const arrayBufferToHexString = (buffer) => {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('').toUpperCase();
}
五、十六进制字符串转ArrayBuffer
c
export let hexStringToArrayBuffer = (str) => {
//十六进制转ArrayBuffer
return new Uint8Array(str.match(/[\da-f]{2}/gi).map(function(h) {
return parseInt(h, 16)
})).buffer
}
六、十六进制转GB2312
c
npm install iconv-lite
c
export let hexToGb2312 = (hexString)=> {
const buffer = Buffer.from(hexString, 'hex');
const decodedString = iconv.decode(buffer, 'GB2312');
return decodedString;
}