Chau Loi
Chau Loi

Reputation: 1225

How to convert byte array to hex string?

Here is the sample code in JS :

function toHexString(bytes) {
  return bytes.map(function(byte) {
      return ("00" + (byte & 0xFF).toString(16)).slice(-2);
    }).join('');
}

input -> Buffer.from("333138383223633D77DB", 'hex')
output -> 333138383223630770

Here is what I have tried so far in Python

def toHexString(byteArray):
    return ''.join('{:02x}'.format(x) for x in byteArray)


input -> bytearray.fromhex("333138383223633D77DB")
output -> 333138383223633d77db

I think the logic is correct but does not know what is wrong

My expectation result of the Python code should be similar to the result of JS code.

I would like to ask how should I update the python code to get the exact result as JS code

Upvotes: 0

Views: 479

Answers (3)

robertklep
robertklep

Reputation: 203534

Your Python code is correct (although it can be written much more concise as the other answers suggest), but your JS code isn't because it clearly outputs a hex string that is not the same as the input.

Instead, fix your JS code:

function toHexString(bytes) {
  return bytes.toString('hex').toUpperCase();
}

input -> Buffer.from("333138383223633D77DB", 'hex')
output -> 333138383223633D77DB

EDIT: if you really insist on Python code that outputs the same broken hex string, this may work:

import re

input  = '333138383223633D77DB';
output = ''
for m in re.finditer(r'..', input):
    match = m.group(0)
    output += match if re.match('[0-9][0-9]', match) else '0'
print(output)

(my Python skills are extremely rusty so it may not work for all inputs, and/or it can be written much more concise)

Upvotes: 1

Adon Bilivit
Adon Bilivit

Reputation: 27296

As has already been stated, there is built-in functionality for this in Python. However, if you insist on re-inventing the wheel then:

hs = '333138383223633D77DB'

def toHexString(ba):
    return ''.join([f'{b:02X}' for b in ba])

assert toHexString(bytearray.fromhex(hs)) == hs

Note the use of uppercase 'X' in the format specifier.

Also worth mentioning that bytearray.hex() returns a string in ASCII lowercase

Upvotes: 1

Endless
Endless

Reputation: 37915

with python 3.5+ you can use hex()

def toHexString(byteArray):
    return byteArray.hex()

honestly do not think there is any need for defining any helper function when you can just run byteArray.hex()

Upvotes: 1

Related Questions