1

If I use a function int.from_bytes() to convert a byte which is in a hexadecimal form it gives me a expected ans. But when the byte is in decimal form I get a unexpected value. I am not able to understand the math behind it, please explain. I am new to this my question may be silly, please try to understand from the example code below.

>>> testBytes = b'\x10'
>>> int.from_bytes(testBytes, byteorder='big', signed=True)
16
>>>testBytes1 = b'10'
>>>int.from_bytes(testBytes1, byteorder='big', signed=True)
12592

Here in the testBytes1 variable expected answer was 10, why I am getting such a big value, how does this function work, how will I get testBytes1 value as integer 10 as it is in the byte form. I am receiving testBytes1 over a usb port.

3 Answers 3

3

That is simply taking the ascii value of each character:

Code:

testBytes1 = b'10'
print(int.from_bytes(testBytes1, byteorder='big', signed=True))

testBytes1 = b'\x31\x30'
print(int.from_bytes(testBytes1, byteorder='big', signed=True))

Results;

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

Comments

1

You can convert bytes to a string, then convert it to an int.

>>> B = b'10'
>>> int(B.decode('utf-8'))
10

Comments

1

The most efficient way according to me is to decode the byte into string, and then converting it further to any required data type. Say, the byte is stored in variable n, then

x = n.decode('utf-8')

x, now will be a string, which can be converted to integer, float, or any data type required, by calling the respective constructor, as int(x)

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.