1

i read many answers about converting hex to binary in SO. I tried to implement it with md5:

import hashlib

c = hashlib.md5("123hello123".encode('ascii'))
print(c.hexdigest())
for _hex in c.hexdigest():
    _hex = int(_hex, 16)
    print(bin(_hex)[2:], end="")

i get the output:

b303fa684382db471658016690101792 1011110111111101011010001001110001011011011100111111010110000111011010010101111100110

where as when i convert in an online converter i get:

10110011000000111111101001101000010000111000001011011000000000000000000000000000000000000000000000000000000000000000000000000000

what is the right answer? how should i correct my program?

moe asal
  • 750
  • 8
  • 24

1 Answers1

2

The bin function does not include leading zeros, while each hex character always represents 4 binary digits. bin(_hex)[2:].rjust(4,"0") will work.

Tesseract
  • 526
  • 3
  • 20
  • While you're at it, you may as well skip the loop entirely and call `bin` on the entire hex digest just once: `print(bin(int(c.hexdigest(), 16))[2:].rjust(128, "0"))` – Kevin Sep 20 '19 at 17:47
  • @Kevin that is worth turning into a separate answer. – Mark Ransom Sep 20 '19 at 17:48