Byte array to Hex string conversion in javascript Byte array to Hex string conversion in javascript arrays arrays

Byte array to Hex string conversion in javascript


You are missing the padding in the hex conversion. You'll want to use

function toHexString(byteArray) {  return Array.from(byteArray, function(byte) {    return ('0' + (byte & 0xFF).toString(16)).slice(-2);  }).join('')}

so that each byte transforms to exactly two hex digits. Your expected output would be 04812d7e3a9829e5d51bdd64ceb35df060699bc1309731bd6e6f1a5443a7f9ce0af4382fcfd6f5f8a08bb2619709c2d49fb771601770f2c267985af2754e1f8cf9


Using map() won't work if the input is of a type like Uint8Array: the result of map() is also Uint8Array which can't hold the results of string conversion.

function toHexString(byteArray) {  var s = '0x';  byteArray.forEach(function(byte) {    s += ('0' + (byte & 0xFF).toString(16)).slice(-2);  });  return s;}


A more concise and performant (see https://jsperf.com/byte-array-to-hex-string) alternative using Array.reduce():

function toHexString(byteArray) {  return byteArray.reduce((output, elem) =>     (output + ('0' + elem.toString(16)).slice(-2)),    '');}

(Also without "& 0xFF" because in my opinion if an array is passed in that contains values larger than 255, the output should be messed up, so that the user can more easily see that their input was wrong.)