Python Forum
converting an int to bytes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
converting an int to bytes
#1
i can convert an int to bytes by first converting to hexadecimal characters (and maybe prefixing a '0' to make an even number of digits). is there any more direct way to convert an int to the binary equivalent sequence of bytes without doing the hexadecimal conversion and/or adjusting the number of hexadecimal digits to a multiple of two.

for those of you that like to have code you can squish in your fingers...

bytes_to_int.py:
t = bytes,bytearray
def bytes_to_int(bytes=None):
    """Convert bytes or bytearray to int."""
    if bytes is None:
        return None
    if isinstance(bytes,t):
        return int.from_bytes(bytes)
    raise TypeError('arg 1 type must be bytes or bytearray')
int_to_bytes.py:
t = int
def int_to_bytes(int=None):
    """Convert int to bytes."""
    if int is None:
        return None
    if isinstance(int,t):
        h=hex(int)[2:]
        if len(h)%2:
            h='0'+h
        return bytes.fromhex(h)
    raise TypeError('arg 1 type must be int')
the above code is not tested, yet. i may test it, some day.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You could could first convert the integer to a list of 'bits', then format some output of that list, maybe in groups of four for the 'bytes', or maybe as a simple stream of 'bits'

dec = 101
bits = [bit for bit in str(bin(dec))[2:]]
print(''.join(bit for bit in bits))
Output:
1100101
Or maybe there's a point here that I'm missing.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#3
Isn't int.to_bytes() the contrary of int.from_bytes()?
Skaperen likes this post
Reply
#4
oooh, i completely missed that one. must have not done the "_" version of the attribute name when i searched.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#5
can you message to me what that link was? i can't remember it from so long ago. i want to figure out if something got 0wn3d.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  converting a number from bytes to float and back Skaperen 3 2,609 Nov-12-2019, 07:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020