Karthikeyan
Karthikeyan

Reputation: 153

Is there any way to get the direct hexadecimal value in bytes instead of getting string value?

In python3.5 I need to convert the string to IPFIX supported field value for UDP packet. While I am sending string bytes as UDP packet I am unable to recover the string data again. In Wireshark, it says that "Malformed data".

I found that IPFIX supports only the "ASCII" for strings. So I have converted ASCII value to hex and then converted into bytes. But while converting hex("4B") to byte. I am not getting my hex value in bytes instead of I am getting the string in bytes("K").

I have tried the following in the python console. I need exact byte what I have entered. But it seems like b'\x4B' instead of '\x4B' I am getting 'K'. I am using python3.5

b'\x4B'

b'K'

Code: "K".encode("ascii")

Actual OP: b'K'

Expected OP: b'\x4B'

Upvotes: 1

Views: 331

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7108

There are multiple ways to do this:

1. The hex method (python 3.5 and up)

>>> 'K'.encode('ascii').hex()
'4b'  # type str

2. Using binascii

>>> binascii.hexlify('K'.encode('ascii'))
b'4b'  # type bytes

3. Using str.format

>>> ''.join('{:02x}'.format(x) for x in 'K'.encode('ascii'))
'4b'  # type str

4. Using format

>>> ''.join(format(x, '02x') for x in 'K'.encode('ascii'))
'4b'  # type str

Note: Methods using format are not very performance efficient.

If you really care about the \x you will have to use format, eg:

>>> print(''.join('\\x{:02x}'.format(x) for x in 'K'.encode('ascii')))
\x4b
>>> print(''.join('\\x{:02x}'.format(x) for x in 'KK'.encode('ascii')))
\x4b\x4b

If you care about uppercase then you can use X instead of x, eg:

>>> ''.join('{:02X}'.format(x) for x in 'K'.encode('ascii'))
'4B'
>>> ''.join(format(x, '02X') for x in 'K'.encode('ascii'))
'4B'

Uppercase and with \x:

>>> print(''.join('\\x{:02X}'.format(x) for x in 'Hello'.encode('ascii')))
\x48\x65\x6C\x6C\x6F

If you want bytes instead of str then just encode the output to ascii again:

>>> print(''.join('\\x{:02X}'.format(x) for x in 'Hello'.encode('ascii')).encode('ascii'))
b'\\x48\\x65\\x6C\\x6C\\x6F'

Upvotes: 1

Related Questions