0

i have a problem.

i get data like:

hex_num='0EE6'
data_decode=str(codecs.decode(hex_num, 'hex'))[(0):(80)]
print(data_decode)
>>>b'\x0e\xe6'

And i want encode this like:

data_enc=str(codecs.encode(data_decode, 'hex'))[(2):(6)]
print(str(int(data_enc,16)))
>>>TypeError: encoding with 'hex' codec failed (TypeError: a bytes-like object is required, not 'str')

If i wrote this:

data_enc=str(codecs.encode(b'\x0e\xe6', 'hex'))[(2):(6)]
print(str(int(data_enc,16)))
>>>3814

It will retrun number what i want (3814)

Please help.

2 Answers 2

1

You can remove the quotation marks like this: data = b'\x0e\xe6'

The Python 3 documentation states:

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

When b is within a string, it will not behave like a string literal prefix, so you have to remove the quotations for the literal to work, and convert the text to bytes directly.

Corrected code:

import codecs
data = b'\x0e\xe6'
data_enc=str(codecs.encode(data, 'hex'))[(2):(6)]
print(str(int(data_enc,16)))

Output:

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

2 Comments

It would be more beneficial to OP if you could explain the reason of that as well
Please don't edit the question, that can make it difficult for future users. If you want to ask another question, post a new question, don't edit the current one!
0

To change from a hex string to binary data, then using binascii.unhexlify is a convenient method. e.g.:

>>> hex_num='0EE6'
>>> import binascii
>>> binascii.unhexlify(hex_num)
b'\x0e\xe6'

Then to convert the binary data to an integer, using int.from_bytes allows you control over the endianness of the data and if it signed. e.g:

>>> bytes_data = b'\x0e\xe6'
>>> int.from_bytes(bytes_data, byteorder='little', signed=False)
58894
>>> int.from_bytes(bytes_data, byteorder='big', signed=False)
3814

Comments

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.