• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / Python to_bytes() – Create Bytes Object from Integer

Python to_bytes() – Create Bytes Object from Integer

October 14, 2022 Leave a Comment

The Python int to_bytes() function allows you to convert integers into an array of bytes representing that integer.

num = 5
num_bytes = num.to_bytes(3, byteorder="big")

print(num_bytes)
print(type(num_bytes))

#Output:
b'\x05'
<class 'bytes'>

When working with different types of objects when programming, the ability to easily be able to convert a variable into a variable of another type is useful.

One such case is if you want to convert an integer to bytes in Python.

The Python to_bytes() function converts integers into bytes.

Bytes are used to save in storage. Byte objects contain data that are machine-readable and we can store a byte object directly into secondary storage.

Typically, when data is saved into storage, it is encoded according to a certain type of encoding such as ASCII, UTF-8, and UTF-16 (strings), PNG, JPG and JPEG (images), and mp3 and wav (audio), and is turned into bytes. When we access the data again, it is decoded into the appropriate data.

to_bytes converts an int object into an array of bytes representing that integer.

to_bytes takes in three arguments.

int.to_bytes(length, byteorder="big", signed=False)

The first argument is the number of bytes you want returned for representing the integer.

The second argument is the order of bytes. You can pass “little” or “big” to “byteorder”. The difference here is passing “little” will result in having the most significant byte at the end of the array, while “big” will result in having the most significant byte at the beginning of the array.

The third argument is used if you have a negative number and want to convert a negative number into bytes.

The rest of the post shows you a number of different examples of how you can use to_bytes() in Python.

Using to_bytes() to Convert Integer into Bytes in Python

Depending on the integer you are trying to convert into bytes, there are different options you can use which will alter the returned bytes object.

Below are a few examples showing you how to vary the number of bytes you want returned to represent a given integer.

num1 = 5
num2 = 10

print(num1.to_bytes(1, byteorder="big"))
print(num1.to_bytes(2, byteorder="big"))
print(num1.to_bytes(3, byteorder="big"))
print(num2.to_bytes(1, byteorder="big"))
print(num2.to_bytes(2, byteorder="big"))
print(num2.to_bytes(3, byteorder="big"))

#Output:
b'\x05'
b'\x00\x05'
b'\x00\x00\x05'
b'\n'
b'\x00\n'
b'\x00\x00\n'

Examples Using to_bytes() byteorder Argument in Python

The byteorder argument to to_bytes() is required and specifies the order of the returned byte array representing the integer.

You can pass “little” or “big” to “byteorder”. The difference here is passing “little” will result in having the most significant byte at the end of the array, while “big” will result in having the most significant byte at the beginning of the array.

Below are a few examples which show the difference between passing ‘little’ and ‘big’ to ‘byteorder’ in Python.

num1 = 5
num2 = 10

print(num1.to_bytes(2, byteorder="big"))
print(num1.to_bytes(2, byteorder="little"))
print(num2.to_bytes(2, byteorder="big"))
print(num2.to_bytes(2, byteorder="little"))

#Output:
b'\x00\x05'
b'\x05\x00'
b'\x00\n'
b'\n\x00'

Something to note is that if your program will be reading bytes at a later time, or these bytes will be used as an input to another process, you should make sure that the byteorder specified matches the expected byteorder to the other program.

Converting Negative Integer to Bytes in Python

If you have negative integers which you want to convert to bytes with to_bytes(), then you have to use the third argument ‘signed’.

If you try to convert a negative integer to bytes, you will get an OverflowError.

In this case, you should pass ‘signed=True’ to get the correct bytes representation.

Below is a simple example of how you can use the “signed” argument with to_bytes().

num = -5

print(num.to_bytes(1, byteorder="little", signed=True))

#Output:
b'\xfb'

Hopefully this article has been useful for you to learn how to convert an integer to a bytes object in Python with to_bytes().

Other Articles You'll Also Like:

  • 1.  How to Add Commas to Numbers in Python
  • 2.  Touch File Python – How to Touch a File Using Python
  • 3.  Calculate Sum of Dictionary Values in Python
  • 4.  pandas covariance – Calculate Covariance Matrix Using cov() Function
  • 5.  Python Add Months to Datetime Variable Using relativedelta() Function
  • 6.  for char in string – How to Loop Over Characters of String in Python
  • 7.  Using Python to Convert Float to Int
  • 8.  Get Username in Python using os module
  • 9.  Replace Character in String in Python
  • 10.  How to Check If Value is in List Using Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy