1

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'
5
  • "... pySerial module, so the hex to ascii is its fundamental." What? No, this makes no sense. Commented Sep 22, 2014 at 5:29
  • well, it requires lots of hex signal indeed. Commented Sep 22, 2014 at 5:34
  • No, not really. It's usually very rare to need the hexadecimal representation. Commented Sep 22, 2014 at 5:50
  • Have you tried: int('de',16) to convert '\xde' to decimal? Commented Sep 22, 2014 at 5:51
  • >>> int('\xde',16) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 16: '\xde' Commented Sep 22, 2014 at 7:34

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

You are right, but why would you want to use such a representation ? The correct hexadecimal string representation for 222 is 0xde, \xde is only the way to write an arbitrary byte value into a string as a synonym for \00de, or to write it directly into a bytearray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.