-2

How i convert number HEX with base 1 (0x1) to base 2 (0x01).

Hex_B1 = 0x1 Hex_B2 = 0x01

hex(int('110', 2)) = 0x06

  • I think you mean you want leading zeros? – Stephen C Nov 12 '18 at 17:34
  • If you Google the phrase "Python convert hex to binary", you’ll find tutorials that can explain it much better than we can in an answer here. – Prune Nov 12 '18 at 17:36
  • You are using the wrong terminology here. Hex is a base 16 numerical notation, *base 2* is binary. You are instead trying to format hexadecimal to using 2 *digits*, padding with zero as needed. – Martijn Pieters Nov 12 '18 at 17:37
  • @GuiLuiz You mean converting _binary_ (base 2) to hex (base 16) ? – p._phidot_ Nov 12 '18 at 17:37

1 Answers1

0

Because hex produces a string, you can just parse the string after conversion to hex.

leading_zeros = 2

str_hex = hex(int('110', 2))
final_hex = '0x'+str_hex[2:].zfill(leading_zeros)

As pointed out by Martijn Pieters in the comments, the much better solution is to use Pythons built in format function.

format(5, '#04x')
Stephen C
  • 1,966
  • 1
  • 16
  • 30