Reputation: 3213
Hi I'm learning pySerial module, so the hex to ascii is its fundamental.
So far I have the following concepts.
Byte String: "\xde"
Byte Array:
>>> bytearray('\xde')
bytearray(b'\xde')
>>> a = bytearray('\xde')
>>> a[0]
222
>>> hex(a[0])
'0xde'
Hex String: '\xde'
Hex: 0xde
Normal representation: de
Now what I need is Hex String to Hex and vice versa.
Also Hex or Hex String to Normal representation .
I wish I can have the simplest possible answer.
Update:
I think I got an initial answer other than string operation. But this looks really dirty.
>>> hex(int(binascii.hexlify('\xde'),16))
'0xde'
Upvotes: 1
Views: 1227
Reputation: 149185
Let me re-write a little.
You have a byte (say b
, with an integer value of 222 (in decimal) or de (in hexadecimal) or 276 in octal or 10111110 in binary.
Its hexadecimal string representation is '0xde'
The following initialisations are the same :
b = 222
b = 0xde
Here are the conversions (say s
is a string, s='0xde'
, ie the hexadecimal string representation)
s = hex(b)
b = int(s, 16)
Edit per comment :
If you really want to be able to accept as input \xde
as well as 0xde
you can do :
b = int('0' + s[1:] if (s[0] == '\\') else s, 16)
or directly
b = int('0' + s[1:], 16)
if you are sure you will never get weird input
Upvotes: 1