Friday, August 12, 2022

[FIXED] How to convert a tuple of bytes to an integer and back?

Issue

Problem: I would like to get

(7,5,3) => 000001110000010100000011 => 460035  
  also the converse, i.e.,   
460035 => 000001110000010100000011 => (7,5,3)

Here is the the program I have tried:

L=(7,5,3) # here L may vary each time.
a=0
for i in range(3):
    a=bin(a << 8) ^ bin(L[i])
print a  

But It gives error TypeError: unsupported operand type(s) for ^: 'str' and 'str'
How can I do this?


Solution

There is no need to reinvent the wheel. If you'd seen the links to docs that I provided in the comments, you could find these useful methods there: int.from_bytes and int.to_bytes. We can use them like this:

input = (7, 5, 3)
result = int.from_bytes(input, byteorder='big')
print(result)
>>> 460035

print(tuple(result.to_bytes(3, byteorder='big')))
>>> (7, 5, 3)


Answered By - Georgy
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.