简体   繁体   中英

How to convert from a decimal to hex in python without using hex()?

I am new here, so please excuse any mistakes I may have made:)

I have been trying to send hex numbers over a virtual serial port pair using Python3 before I can test it on an actual device. However, the only ways to work with hex numbers I have found so far are:

a) Use them as a regular string

num_hex = input()

But this does not allow me to work on the numbers, as num_hex is a string

.

b) Convert them using int(,16)

ip_hex = input()
num_ip_hex = int(ip_hex, 16)
print(ip_hex, num_ip_hex, hex(num_ip_hex))

When used here num_ip_hex just store numbers in the form of base 10. For example the output for the print statement with input 'a' is

input[]: a
output[]: a 10 0xa

.

c) Use hex() and then use them

ip = input(">> ")
ip=int(ip, 16)
ip=hex(ip)

Again, this also gives a string.

I need a way to receive hex numbers and to be able to work with them further in that exact same way, not as strings or decimals. Is this possible?

EDIT: In short some form of hex that i can work with to like add, subtract, shift left etc.

I think the closest you can get is storing data as bytes. Bytes actually have a built in method in python .hex() so you can always see a hex representation of it.

my_bytes = b'some words'
my_bytes.hex()   #'736f6d6520776f726473'

If you are sending the data raw as bytes, you could then do a direct comparison without worrying about hex at all. However, if you want to still send the hex as a string, you will need binascii.unhexlify()

import binascii
binascii.unhexlify('736f6d6520776f726473')    # b'some words'

Though it is generally preferred to send bytes, as then you do not have to worry about encoding and other issues.

Hope this helps!

Edit: Wanted to add dealing directly with the code you provided, it would look something like:

 comparable_bytes = b'verify_me'
 comparable_hex = '7665726966795f6d65'

 ip_hex = binascii.unhexlify(input('>> '))  # Input the Hex numbers

 assert ip_hex == comparable_bytes
 assert ip_hex.hex() == comparable_hex

Edit 2: Multiple hex character input

# Remove whitespace, allow for entry with or without spaces
ip = input().strip().replace(' ', '') 

bytestring  = binascii.unhexlify(ip)

Then you can directly send bytestring .

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