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
380 views
in Technique[技术] by (71.8m points)

javascript - Why doesn't Uint8Array.toString('hex') return hex?

Given this (based on another answer):

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

console.log(fromHexString('a0e30c9e46d8f973f4082d79fce1fb46b1c199bb047bb3545c85b545f7a1650a').toString('hex'))

//expected "a0e30c9e46d8f973f4082d79fce1fb46b1c199bb047bb3545c85b545f7a1650a"

//get "160,227,12,158,70,216,249,115,244,8,45,121,252,225,251,70,177,193,153,187,4,123,179,84,92,133,181,69,247,161,101,10"
question from:https://stackoverflow.com/questions/65851192/why-doesnt-uint8array-tostringhex-return-hex

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

1 Reply

0 votes
by (71.8m points)

A typed array has a toString method that takes no argument, so providing 'hex' to it will have no influence, it will just join the values into a comma-separated list of the values in decimal representation.

To get hexadecimal output, you'll need to iterate the array and convert each value to hex and concatenate the result:

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

const toHexString = arr => Array.from(arr, i => i.toString(16).padStart(2, "0")).join("");

const arr = fromHexString('a0e30c9e46d8f973f4082d79fce1fb46b1c199bb047bb3545c85b545f7a1650a');

console.log(toHexString(arr));

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

...