PHP函数有 bin2hex和hex2bin,下面为JS的相同功能实现。
function bin2hex(str) {
const encoder = new TextEncoder();
const bytes = encoder.encode(str);
let hex = '';
for (const byte of bytes) {
hex += byte.toString(16).padStart(2, '0');
}
return hex;
}
function hex2bin(hex) {
let result = '';
if (/^[0-9a-fA-F]*$/.test(hex)) {
if (hex.length % 2 !== 0) {
hex = '0' + hex;
}
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
}
result = new TextDecoder().decode(bytes);
}
return result;
}
本文对您如有帮助,请在本文下面“点赞”支持一下,谢谢!
全文结束【EOF】