Reputation: 19
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.
Upvotes: 1
Views: 437
Reputation:
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)
Upvotes: 1
Reputation: 432
You can convert bytes to a string, then convert it to an int.
>>> B = b'10'
>>> int(B.decode('utf-8'))
10
Upvotes: 1
Reputation: 49842
That is simply taking the ascii value of each character:
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))
12592
12592
Upvotes: 3