MATLAB
MATLAB

Reputation: 13

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

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?

Upvotes: 1

Views: 1216

Answers (2)

Georgy
Georgy

Reputation: 13737

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)

Upvotes: 2

blhsing
blhsing

Reputation: 106945

You should perform bit operations on the numbers rather than the converted strings:

L=(7,5,3)
a=0
for i in L:
    a <<= 8
    a |= i
print(bin(a), a)

This outputs:

0b1110000010100000011 460035

Reversal:

a = 460035
L = []
while True:
    L.append(a & 0xff)
    a >>= 8
    if not a:
        break
L = tuple(L[::-1])
print(L)

This outputs:

(7, 5, 3)

Upvotes: 0

Related Questions