js 将十进制字符串转换成4字节的字节数组

函数

function convertToHexArrays(input) {
    // 通过制表符分割输入字符串
    const numbers = input.split('\t');
    // 用于存储结果的数组
    const result = [];
    for (let num of numbers) {
        // 将字符串转换为数字
        const value = parseInt(num);
        // 创建一个 4 字节的 ArrayBuffer
        const buffer = new ArrayBuffer(4);
        // 创建一个视图来操作这个 buffer
        const view = new DataView(buffer);
        // 将数值写入 buffer(使用小端序)
        view.setUint32(0, value, true);
        // 将 buffer 转换为十六进制字符串
        const hexArray = Array.from(new Uint8Array(buffer))
            .map(b => b.toString(16).padStart(2, '0'))
            .join(' ');
        result.push(hexArray);
    }
    return result;
}

使用

const hexArrays = convertToHexArrays(`76    1045220557    81    1045220557    96    1045220557    100    1045220557    101    1045220557    102    1045220557`);
console.log(hexArrays.join(' '))
//4c 00 00 00 cd cc 4c 3e 51 00 00 00 cd cc 4c 3e 60 00 00 00 cd cc 4c 3e 64 00 00 00 cd cc 4c 3e 65 00 00 00 cd cc 4c 3e 66 00 00 00 cd cc 4c 3e

 

posted @ 2024-08-07 20:18  herry菌  阅读(5)  评论(0编辑  收藏  举报