1

I'm using this function to convert byte array to hex string:

function toHexString(bytes)
 {
  return bytes.map(function (byte)
   {
    return (byte & 0xFF).toString(16)
   }).join('')
 }

The issue is that function write bytes <=15 (F in hex) in one character for example:

  • 10 --> A (but i want to write 0A)

Any Ideas?

Abdessamad Doughri
  • 1,324
  • 2
  • 16
  • 29

2 Answers2

2

If byte is below 16, toString(16) returns one character, so you have to prepend the desired zero. Else if byte is 16 or more, you may use your original code, because toString(16) returns two characters.

if (byte < 16)
    return '0' + byte.toString(16);
else
    ...
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

You can do something like this:

function toHexString(bytes) {
    var result = bytes.map(function (byte) {
    if(byte>15)
        return (byte & 0xFF).toString(16)
    else
        return '0'+(byte & 0xFF).toString(16)
     }).join('')
}

Just check the byte value if it's greater than 15 if not add 0 to the result.

chris Frisina
  • 19,086
  • 22
  • 87
  • 167
manecosta
  • 8,682
  • 3
  • 26
  • 39
  • That works just when I've one byte to convert not for byte array but I solve this like so: if(byte>15) return (byte & 0xFF).toString(16) else return '0'+(byte & 0xFF).toString(16) – Abdessamad Doughri Nov 17 '15 at 15:33