Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to hex in Python? [duplicate]

Tags:

python

hex

I using the pyqt5 line edit box as my input boxes. I want to take the input from the input boxes and convert it from string to hex to send to serial capture. For example I did this but I didn't succeed:

a = hex(self.slave1.text())
b = hex(self.function1.text())
c = hex(self.address_msb1.text())
d = hex(self.address_lsb1.text())
e = hex(self.register_msb1.text())
f = hex(self.register_lsb1.text())
g = hex(self.crc_lsb1.text())
h = hex(self.crc_msb1.text())
hexConvert = [a,b,c,d,e,f,g,h]

Imagine:

a = "01"
b = "03"
c = "00"
d = "0A"
e = "00"
f = "04"
g = "64"
h = "0B"

And my expected output is

[0x01, 0x03, 0x00, 0x0A, 0x04, 0x64, 0x0B]
like image 398
CripsyBurger Avatar asked Apr 18 '26 02:04

CripsyBurger


1 Answers

The hex() function converts a specified integer number into a hexadecimal string representation.

Use int(x, base) with 16 as base to convert the string x to an integer. Call hex(number) with the integer as number to convert it to hexadecimal.

hex_string = "0xAA"

"0x" also required

an_integer = int(hex_string, 16)

hex_value = hex(an_integer)

print(hex_value)

Output

0xaa

like image 61
Thuấn Đào Minh Avatar answered Apr 19 '26 15:04

Thuấn Đào Minh