Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert Hex String to Bytes in Python
Next article icon

How to Convert Int to Bytes in Python?

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of converting an integer to bytes in Python involves representing a numerical value in its binary form for storage, transmission, or processing. For example, the integer 5 can be converted into bytes, resulting in a binary representation like b’\x00\x05′ or b’\x05′, depending on the chosen format.

Using int.to_bytes()

.to_bytes() method is the most direct way to convert an integer to bytes. It allows specifying the byte length and byte order (big for big-endian, little for little-endian).

Python
a = 5  res = a.to_bytes(2, 'big')  # length: 2 bytes, byte order: Big-endian print(res) 

Output
b'\x00\x05' 

Explanation: Here, 2 ensures a fixed 2-byte representation, adding a leading zero-byte (\x00) for padding. ‘big’ specifies big-endian order, storing the most significant byte first.

Table of Content

  • Using struct.pack()
  • Using bytes()
  • Using bytes.fromhex()

Using struct.pack()

struct.pack() function is used for packing integers into bytes using format specifiers. The “>H” format specifies a big-endian 2-byte unsigned short, ensuring a structured binary representation.

Python
import struct a = 5  res = struct.pack(">H", a)  # '>H' -> big-endian Unsigned Short (2 bytes) print(res)  

Output
b'\x00\x05' 

Explanation: Here, H represents an unsigned short (2 bytes) and > ensures big-endian order, storing the most significant byte first. Since 5 is smaller than 256, a leading zero-byte (\x00) is added for proper 2-byte representation.

Using bytes()

bytes() function can be used to create a single-byte representation of an integer. This method works only for values between 0 and 255 because a single byte can store values in this range.

Python
a = 5  res = bytes([a])  # converts single integer to a 1-byte representation print(res) 

Output
b'\x05' 

Explanation:bytes([a]) converts 5 into a 1-byte object since it falls within the 0-255 range, meaning no padding is needed.

Using bytes.fromhex()

This method first converts an integer to a hex string, ensuring it is properly padded and then converts it into a bytes object. It is useful when dealing with hex-based data representation.

Python
a = 5  res = bytes.fromhex(hex(a)[2:].zfill(2))  # ensures 2-digit hex representation print(res) 

Output
b'\x05' 

Explanation: hex(a)[2:] removes the 0x prefix, .zfill(2) ensures a 2-digit hex format and bytes.fromhex() converts it into a byte object (b’\x05′) .



Next Article
Convert Hex String to Bytes in Python

Y

yashkumar0457
Improve
Article Tags :
  • Python
  • python-basics
Practice Tags :
  • python

Similar Reads

  • How to Convert Bytes to Int in Python?
    Converting bytes to integers in Python involves interpreting a sequence of byte data as a numerical value. For example, if you have the byte sequence b'\x00\x01', it can be converted to the integer 1. Using int.from_bytes()int.from_bytes() method is used to convert a byte object into an integer. It
    3 min read
  • How to Convert Bytes to String in Python ?
    We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'. This article covers different ways to convert bytes into strings in Py
    2 min read
  • How to convert Float to Int in Python?
    In Python, you can convert a float to an integer using type conversion. This process changes the data type of a value However, such conversions may be lossy, as the decimal part is often discarded. For example: Converting 2.0 (float) to 2 (int) is safe because here, no data is lost.But converting 3.
    5 min read
  • Convert Hex String to Bytes in Python
    Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. The task of converting a hex string to bytes in Python can be achieved using various methods. Below, are the ways to convert hex string to bytes in Python. Using by
    2 min read
  • Convert Unicode to Bytes in Python
    Unicode, often known as the Universal Character Set, is a standard for text encoding. The primary objective of Unicode is to create a universal character set that can represent text in any language or writing system. Text characters from various writing systems are given distinctive representations
    2 min read
  • How to convert string to integer in Python?
    In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equiv
    3 min read
  • How To Convert Unicode To Integers In Python
    Unicode is a standardized character encoding that assigns a unique number to each character in most of the world's writing systems. In Python, working with Unicode is common, and you may encounter situations where you need to convert Unicode characters to integers. This article will explore five dif
    2 min read
  • Convert Bytes To Bits in Python
    The task of converting bytes to bits in Python can be efficiently done by multiplying the number of bytes by 8, as 1 byte equals 8 bits. Additionally, methods like bit_length() and others can also be used to achieve this conversion. Example: [GFGTABS] Python def b2b(bv): return bv * 8 bv = 4 br = b2
    3 min read
  • Convert String to Int in Python
    In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
    3 min read
  • Convert Hex String To Integer in Python
    Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this tas
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences