Python int to 4 bytes

In case anyone looks at this question sometime later ...
This statement should be equivalent to the code in the original question:

>>> tuple( struct.pack("!I", number) )
('\x00', '\x00', '\x00', 'd')

And I don't think it matters what the host byte order is.
If your integers are larger than int32, you can use "!Q" in the call to pack() for int64 (if your system supports Q).
And list() or even bytearray() will work in place of tuple().

Note, the result is a sequence of str objects (each holding a single byte), not integers. If you must have a list of integers, you can do this:

[ ord(c) for c in struct.pack("!I", number) ]
[0, 0, 0, 100]

... or this:

>>> map( ord, tuple( struct.pack("!I", number) ) )
[0, 0, 0, 100]

But using map() starts making things a bit messy.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. 

    Method 1: int.tobytes()

    An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

    Syntax: int.to_bytes(length, byteorder)

    Arguments

    length – desired length of the array in bytes .

    byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. 

    Exceptions : 

    OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array. 

    The following programs illustrate the usage of this method in Python : 

    Python3

    integer_val = 5

    bytes_val = integer_val.to_bytes(2, 'big')

    print(bytes_val)

    Python3

    integer_val = 10

    bytes_val = integer_val.to_bytes(5, 'little')

    print(bytes_val)

    Output

    b'\n\x00\x00\x00\x00'

    Method 2: Converting integer to string and string to bytes 

    This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments. 

    • An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent.
    • This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method.

    Python3

    int_val = 5

    str_val = str(int_val)

    byte_val = str_val.encode()

    print(byte_val)


    Greetings everyone. I'm a relative newcomer to python and I have a technical
    problem.

    I want to split a 32 bit / 4 byte unsigned integer into 4 separate byte
    variables according to the following logic: -

    bit numbers 0..7 byte 1
    bit numbers 8..15 byte 2
    bit numbers 16..23 byte 3
    bit numbers 24..31 byte 4

    Each of these byte variables to contain integer data from 0 to 255 (or 0 to
    FF in hex mode)

    I had thought that struct.unpack with an input message format of 'I' would
    be the way to do it, but its reporting an error that it doesn't want to
    accept an integer.

    Please can anyone advise?

    May 11 '07 #1

    Python int to 4 bytes

    Python 3.2 now has a function called int.from_bytes() to convert bytes to an integer. To create bytes in Python, use the bytes() method. The bytes() is a built-in method that returns immutable bytes object initialized with the given size and data.

    To convert bytes to int in Python, use the int.from_bytes() method. A byte value can be interchanged to an int value using the int.from_bytes() function.

    The int.from_bytes() function takes bytes, byteorder, signed, * as parameters and returns the integer represented by the given array of bytes.

    Syntax

    int.from_bytes(bytes, byteorder, *, signed=False)

    Arguments

    bytes: It is a byte object.

    byteorder: It determines the order of representation of the integer value. The byteorder can have values as either “little,” where the most significant bit is stored at the end of “big”, where MSB is stored at the start, and LSB at the end.

    signed: It has a False default value. It indicates whether to represent 2’s complement of a number.

    Return Value

    It returns the integer represented by the given array of bytes.

    Example

    # Declaring byte value
    byte_val = b'\x21\x19'
    
    # Converting to int
    int_val = int.from_bytes(byte_val, "big")
    
    # printing int equivalent
    print(int_val)

    Output

    8473

    You can see that we passed byteorder = big. The byteorder argument determines the byte order used to represent the integer. If byteorder is “little“, the most significant byte is at the beginning of the byte array.

    Passing byteorder = “little”

    If byteorder is “little“, the most significant byte is at the end of the byte array.

    # Declaring byte value
    byte_val = b'\x11\x21'
    
    # Converting to int
    int_val = int.from_bytes(byte_val, "little")
    
    # printing int equivalent
    print(int_val)

    Output

    8465

    Passing signed=True

    The int.from_bytes() method also accepts the signed argument. By default, its value is False.

    Let’s another example and pass signed = True and see the output.

    # Declaring byte value
    byte_val = b'\xfc\x00'
    
    # Converting to int
    int_val = int.from_bytes(byte_val, "big", signed=True)
    
    # printing int equivalent
    print(int_val)

    Output

    -1024

    I hope you found the answer you are looking for, and That is it for converting bytes to integer in Python example.

    See also

    Python string to int

    Python string to hex

    Python string to dictionary

    Python string to json

    Python string to array

    How do you convert int to byte in Python?

    An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

    How many bytes is an int in Python?

    To be safe, Python allocates a fixed number of bytes of space in memory for each variable of a normal integer type, which is known as int in Python. Typically, an integer occupies four bytes, or 32 bits.

    What does byte () do in Python?

    Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.

    How do you convert int to bytes manually?

    Use Convert. ToByte(intValue) which will convert your integer value to byte. If the entered value is too big or too small, it will through OverFlowException. Better to use the Byte.