0

Through the code for i in range(2000,50000) I want to output the numbers from 2000 to 50000 in the following string format:

when i = 2000 output : 07 D0 When i = 50000 output : C3 50

How can I do that?

Sliced_ice
  • 37
  • 4
  • 1
    Does this answer your question? [How to convert an int to a hex string?](https://stackoverflow.com/questions/2269827/how-to-convert-an-int-to-a-hex-string) – Tobi208 Jan 25 '22 at 08:35
  • you need learn integer types first ! S16,U16,S32,U64,F32,F64 etc. Another point which byte-order (big-little), so this comment a answer, use *struct* – dsgdfg Jan 25 '22 at 08:35
  • 1
    Does this answer your question? [Python convert decimal to hex](https://stackoverflow.com/questions/5796238/python-convert-decimal-to-hex) – Pavel Schiller Jan 25 '22 at 08:36

2 Answers2

0

You can try this way:

def format_hex(number):
    # convert to hex string
    hex_str = hex(number)

    # upper case
    hex_str_upper = hex_str.upper()

    # format 
    hex_value = hex_str_upper[2:]
    if len(hex_value)==3:
        hex_value = '0' + hex_value
    hex_value_output = hex_value[:2] + ' ' + hex_value[2:]

    return hex_value_output
bao.le
  • 146
  • 1
  • 4
0

Try:

def format_hex(i: int) -> str:
    h = hex(i)[2:]
    h = h.zfill(len(h) + len(h) % 2).upper()
    return ' '.join(h[i:i+2] for i in range(0, len(h), 2))

Usage:

>>> print(format_hex(2000))
07 D0

>>> print(format_hex(50000))
C3 50
Corralien
  • 109,409
  • 8
  • 28
  • 52