Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

ramda.js - How to convert a hexadecimal string to Uint8Array and back in JavaScript?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'))

Note: this method trusts its input. If the provided input has a length of 0, an error will be thrown. 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 or empty (e.g. user input), check its length and handle the error before calling this method, e.g.:

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

Source: the Libauth library (hexToBin method)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...