js 把Hex转换 16 进制数据为字节数据去掉多余空白再转base64
你可以使用以下代码将Hex转换为字节数据,并将其转换为Base64:
function hexToBytes(hex) {
const bytes = [];
for (let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
return new Uint8Array(bytes);
}
function removeWhitespace(str) {
return str.replace(/\s/g, '');
}
function bytesToBase64(bytes) {
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
const hexData = '48656c6c6f20576f726c6421'; // Hex数据
const bytes = hexToBytes(removeWhitespace(hexData));
const base64Data = bytesToBase64(bytes);
console.log(base64Data);
这段代码首先定义了一个hexToBytes函数,它将输入的Hex字符串转换为字节数据。然后,removeWhitespace函数用于移除Hex字符串中的多余空白。接下来,bytesToBase64函数将字节数据转换为Base64字符串。最后,你可以使用提供的Hex数据调用这些函数,并打印输出Base64数据。
原文地址: https://www.cveoy.top/t/topic/ijvw 著作权归作者所有。请勿转载和采集!