JS版的bin2hex和hex2bin,支持Unicode汉字

本文提供了一种在JavaScript中手动实现二进制到十六进制(bin2hex)及十六进制到二进制(hex2bin)转换的方法。通过自定义函数,弥补了JavaScript中缺乏类似PHP bin2hex和hex2bin函数的不足。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值