10

I can generate a byte array with

var myByteArray = window.crypto.getRandomValues(new Uint8Array(16))

and I get

181,143,16,173,231,56,63,149,181,185,224,124,84,230,123,36

I can then turn this into a string with

cryptoHelpers.convertByteArrayToString(myByteArray);

and i get

µ­ç8?µ¹à|Tæ{$

But what I really want is a 128 bit hexadecimal like...

6a3e52297b2e593f4d506f7164

And I want to be able to go back from hexadecimal to a byte array.

Is there a copy and paste function or library to make this magic happen?

3
  • 3
    I'm voting to close this question as off-topic because it is unrelated to Bitcoin.
    – Claris
    Oct 12, 2018 at 11:25
  • You should ask this question on Stackoverflow, however search first. I'm positive the answer will already exist.
    – Jestin
    Oct 17, 2018 at 18:15
  • I'm voting to close this question as off-topic because, the question, as written, does not appear related to bitcoin. Perhaps there is a relation, but if so, it should be made explicit.
    – dbkeys
    Oct 20, 2018 at 9:53

1 Answer 1

12

Here's something you can copy-paste in.

byteArray = new Uint8Array([181,143,16,173,231,56,63,149,181,185,224,124,84,230,123,36]);
function toHexString(byteArray) {
  return Array.prototype.map.call(byteArray, function(byte) {
    return ('0' + (byte & 0xFF).toString(16)).slice(-2);
  }).join('');
}
function toByteArray(hexString) {
  var result = [];
  for (var i = 0; i < hexString.length; i += 2) {
    result.push(parseInt(hexString.substr(i, 2), 16));
  }
  return result;
}
hexString = toHexString(byteArray);
byteArray = toByteArray(hexString);

From here/here.

4
  • Using the above I'm getting a string that is not 128bits 289332005600940420022031 if I console log myByteArray i get an array buffer like "Uint8Array(16) [181, 143, 16, 173, 231, 56, 63, 149, 181, 185, 224, 124, 84, 230, 123, 36]" how do i convert this to an array? Apr 12, 2017 at 4:12
  • @Will-In-China See edit.
    – Nick ODell
    Apr 12, 2017 at 4:19
  • toByteArray get wrong values when hex-string contains an odd number of characters: "fff", "1AB"
    – Geograph
    Apr 12, 2018 at 15:55
  • 2
    @Geograph since each byte is 2 hex digits, this is expected behaviour - a hex string with an odd number of digits is in invalid hex string. Oct 10, 2018 at 10:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.