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

Tuesday, July 19, 2022

[FIXED] How to cast bytes to an int and back to the same bytes?

 July 19, 2022     byte, casting, integer, python, python-3.x     No comments   

Issue

I have an arbitrary byte in Python that I want to cast into a 64 bit integer and back into the same byte.

I am currently, using this to turn the bytes into an int, where x is a byte I am given:

int.from_bytes(x, "little")

But I'm struggling on how to use int.to_bytes() to convert it back to the same bytes because I'm unsure what to put for length, nothing seems to create the equivalent byte?


Solution

I may not understand you question, but consider this:

x = b'deadbeef'
print(f'x -> {x}')    # x -> b'deadbeef'

i = int.from_bytes(x, 'little')
print(f'i -> {i:,}')  # i -> 7,378,415,037,781,730,660

y = i.to_bytes(len(x), 'little')
print(f'y -> {y}')    # y -> b'deadbeef'


# If you don't know the original variable, you can compute the byte length
# like this:

bit_length = i.bit_length() + 1  # Including sign bit.
byte_length = (bit_length + 7) // 8

z = i.to_bytes(byte_length, 'little')
print(f'z -> {z}')    # z -> b'deadbeef'


Answered By - martineau
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • 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