简体   繁体   中英

How can I get the string of 5 digit hexadecimal in Python?

I have an integer that I converted to hexadecimal as follows:

  int_N = 193402
  hex_value = hex(int_N)

it gives me the following hex: 0x2f37a .

I want to convert the hexadecimal to string .

I tried this:

  bytes.fromhex(hex_value[2:]).decode('ASCII')
  # [2:] to get rid of the 0x

however, it gives me this error:

   UnicodeDecodeError: 'ascii' codec can't decode byte 0xf6 in position 1: ordinal not in range(128)

Then I tried with decode('utf-8') instead of ASCII , but it gave me this error:

   UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1: invalid start byte

Any suggestions how to fix that? whay it's not converting the hexadecimal '0x2f37a' to a string?

After reading some documentations, I assume maybe Hexadecimal should contain even number of digits in order to covert to string, but wasn't able to do so or make it even, as I'm using hex() and it gave me the value.

Thanks and really appreciate any help!

I assume (maybe wrongly) that your int_N is an unicode codepoint.

>>> int_N = 193402
>>> chr(int_N)
'\U0002f37a'

You should look at the struct and binascii module.

import struct
import binascii

int_N = 193402

s      = struct.Struct(">l")
val    = s.pack(int_N)
output = binascii.hexlify(val)

print(output) #0002f37a

find out more about c_type packing here at PMOTW3 .

If you simply want to convert it to a string, no other requirements, then this works (I'll pad it to 8 characters here):

int_N = 193402
s = hex(int_N)[2:].rjust(8, '0') # get rid of '0x' and pad to 8 characters
print(s, type(s))

Output:

0002f37a <class 'str'>

...proving that it's a string type. If you're interested in getting the individual bytes , then something like this will demonstrate:

for b in bytes.fromhex(s):
    print(b, type(b))

Output:

0 <class 'int'>
2 <class 'int'>
243 <class 'int'>
122 <class 'int'>

... showing all four bytes (from eight hex digits) and proving they're integers. The key here is an even number of characters I chose 8) so that fromhex() can decode it. An odd number of bytes will give a ValueError .

Now you can either use the string or the bytes as you please.

Format numbers the way you like with f-strings (format strings). Here are examples of various forms of hexadecimal and binary:

>>> n=193402
>>> f'{n:x} {n:08x} {n:#x} {n:020b}'
'2f37a 0002f37a 0x2f37a 00101111001101111010'

See Format Specification Mini-Language .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM