-2

I'm trying to add the real hexa syntax to an hexa value... For example :

First I convert a decimal value to hexa :

4480 decimal to hexa = 0x1180

following I want to convert this hexa value to this format : 0x80 0x11

What the best way to do that ? Does exist a reverse concatenate function ? in Python ?

Thanks.

wanwan
  • 55
  • 1
  • 7
  • Does this answer your question? [Convert a Python int into a big-endian string of bytes](https://stackoverflow.com/questions/846038/convert-a-python-int-into-a-big-endian-string-of-bytes) (except in your case you want `byteorder='little'` – Pranav Hosangadi Jun 12 '23 at 13:41
  • *How* did you "convert a decimal value to hexa"? Maybe it could be adapted to your overall problem. – Scott Hunter Jun 12 '23 at 13:50
  • It isn't clear exactly what your outputs are supposed to be, just a string? Why not provide the precise output? – juanpa.arrivillaga Jun 12 '23 at 16:01

3 Answers3

0

You can convert an int to a hexadecimal string using the built-in hex() function. The problem with that is you get a prefix of '0x' which you may not want. Also, in this case, you need exactly 4 hexadecimal digits.

An f-string might be more appropriate. Something like this:

def hconv(i: int) -> tuple[str, ...]:
    h = f'{i:04x}'
    return '0x'+h[2:], '0x'+h[:2]

print(hconv(4480))

Output:

('0x80', '0x11')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

thank for replying to me. I have another question :

Is this code the best to return hexa from int value. To be more clear, my input is for example (int value) : 99999999
and what I need is that values : 0x5f 0x5e 0x0f 0xf0

The code I use is :

h=99999999
k=hex(h)
print('0x'+k[2:4], '0x'+k[4:6], '0x'+k[6:8], '0x'+k[8:10])

result is : 0x5f 0x5e 0x0f 0xf

Do you think this code is the best way ?? Thank you.

wanwan
  • 55
  • 1
  • 7
-1

My answer :

a = int(input(" entrer une valeur a convertir (volts): "))

if a!=0 :
    b=a*40
    print(" -> a x 40 = ", b)
    c=hex(b)
    print(" -> hex (", b ,") = ", c)
    a=hex(b >> 8)
    b=hex(b & 0xFF)
wanwan
  • 55
  • 1
  • 7