如何将十六进制字符串转换为Uint8Array并返回JavaScript? [英] How to convert a hexadecimal string to Uint8Array and back in JavaScript?

查看:887
本文介绍了如何将十六进制字符串转换为Uint8Array并返回JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 bada55 之类的十六进制字符串转换为 Uint8Array ,然后再返回。

I want to convert a hexadecimal string like bada55 into a Uint8Array and back again.

推荐答案

Vanilla JS:

Vanilla JS:

const fromHexString = hexString =>
  new Uint8Array(hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));

const toHexString = bytes =>
  bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');

console.log(toHexString(new Uint8Array([0, 1, 2, 42, 100, 101, 102, 255])))
console.log(fromHexString('0001022a646566ff'))

注意:此方法始终完成。如果十六进制编码缓冲区的长度不能被2整除,那么将解析最后一个字节,好像它前面加上 0 (例如 aaa 被解释为 aa0a )。

Note: this method always completes. If the length of the hex-encoded buffer is not divisible by 2, the final byte will be parsed as if it were prepended with a 0 (e.g. aaa is interpreted as aa0a).

如果十六进制可能格式错误(例如用户输入),在调用此方法之前检查其长度并处理错误,例如:

If the hex is potentially malformed (e.g. user input), check its length and handle the error before calling this method, e.g.:

const missingLetter = 'abc';
if(missingLetter.length % 2 === 0){
  throw new Error(`The string "${missingLetter}" is not divisible by 2.`)
}
fromHexString(missingLetter);

这篇关于如何将十六进制字符串转换为Uint8Array并返回JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆