45678 / Base58

Base58 encoding & decoding for Node.js & web agent windows.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to convert Uint8Array into a string?

youfeed opened this issue · comments

I don't know how Uint8Array is converted to a string, I need to restore the string for transmission.

Can you help me? I need to convert the hex address of the private key into base58, now I need to decode base58 into hex~

@youfeed


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

function fromHexString(hex) {
   hex = hex.toString();
   var bytes = new Uint8Array(hex.length / 2);
   for(var i=0; i< hex.length-1; i+=2) {
      var c = parseInt(hex.substr(i, 2), 16);
      if (c > 127) {
         c = c - 256;
      }
      bytes[i/2] = c;
   }
   return bytes;
}

That "c - 256" converts Uint8 to Int8, otherwise you get weird results.

A) If you want to use Base58.decode(), pass the result to toHexString()
B) Before you pass something to Base58.encode(), pass it through fromHexString()