PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

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

 August 12, 2022     binary, decimal, python, string, tuples     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing