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 Unicode to Bytes in Python
Next article icon

How to Convert Bytes to Int in Python?

Last Updated : 08 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 allows specifying the byte order (either ‘big’ or ‘little’) and whether the integer is signed or unsigned.

Syntax:

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

Parameter:

  • bytes: A byte object.
  • byteorder :”big” (MSB first) or “little” (LSB first).
  • signed : False (default) for unsigned integers, True for signed integers.

Returns: An int equivalent to the given bytes.

Example:

Python
# Using Big-endian byte order byte_val_1 = b'\x00\x01' res_1 = int.from_bytes(byte_val_1, "big") print(res_1)  # Using Little-endian byte order byte_val_2 = b'\x00\x10' res_2 = int.from_bytes(byte_val_2, "little") print(res_2)  # Using Signed Integer Representation byte_val_3 = b'\xfc\x00' res_3 = int.from_bytes(byte_val_3, "big", signed=True) print(res_3) 

Output
1 4096 -1024 

Explanation:

  • Big-endian (b’\x00\x01′): The most significant byte (0x00) comes first, followed by 0x01. This gives the result 1 because 0x00 * 256 + 0x01 = 1.
  • Little-endian (b’\x00\x10′): The least significant byte (0x10) comes first, followed by 0x00. In little-endian, 0x10 represents 4096 because 0x10 * 256 = 4096.
  • Signed integer (b’\xfc\x00′): Interpreting the bytes as a signed integer gives -1024. Here, 0xfc represents a negative number in two’s complement (a representation for signed integers).

Table of Content

  • Using struct.unpack()
  • Using numpy.frombuffer

Using struct.unpack()

The struct.unpack() function is part of Python’s struct module. It unpacks a byte object into a tuple of values according to the format specified.

Syntax:

struct.unpack(format, bytes)

Parameters:

  • format: A format string (‘>H’ for big-endian, <H for little-endian, >I for 4-byte integer, etc.).
  • bytes : A byte object.

Returns: A tuple containing the unpacked integer.

Example:

Python
import struct  # Unpacking a 2-byte unsigned short (big-endian) byte_data = b'\x01\x02' res_1 = struct.unpack('>H', byte_data)[0]   print(res_1)   # Unpacking a 4-byte unsigned int (little-endian) byte_data = b'\x01\x00\x00\x00' res_2 = struct.unpack('<I', byte_data)[0]   print(res_2)   # Unpacking a signed 4-byte integer (big-endian) byte_data = b'\xff\xff\xff\xfc' res_3 = struct.unpack('>i', byte_data)[0] print(res_3)  

Output
258 1 -4 

Explanation:

  • Big-endian (b’\x01\x02′): The format string ‘>H’ unpacks the two bytes as a big-endian unsigned short. 0x01 * 256 + 0x02 gives 258.
  • Little-endian (b’\x01\x00\x00\x00′): The format string ‘<I’ unpacks the 4-byte integer as little-endian. The value is 0x01 in little-endian, which is 1.
  • Signed integer (b’\xff\xff\xff\xfc’): The format string ‘>i’ unpacks the 4 bytes as a signed integer. The value is interpreted as -4 in two’s complement form.

Using numpy.frombuffer

If you’re working with large amounts of binary data, numpy provides a convenient method called frombuffer() to convert byte data into an array. It also allows you to specify the byte order and data type.

numpy.frombuffer(bytes, dtype)

Parameters:

  • bytes: The byte object to be interpreted.
  • dtype: The data type for the conversion (e.g., ‘>u2’ for big-endian unsigned short).

Returns: A numpy array containing the interpreted data.

Python
import numpy as np  # Big-endian unsigned short (2 bytes) byte_data = b'\x01\x02' res_1 = np.frombuffer(byte_data, dtype='>u2')[0]   print(res_1)    # Big-endian signed int (4 bytes) byte_data = b'\x01\x00\x00\x00' res_2 = np.frombuffer(byte_data, dtype='>i4')[0]   print(res_2)   # Little-endian unsigned int (4 bytes) byte_data = b'\x01\x00\x00\x00' res_3 = np.frombuffer(byte_data, dtype='<u4')[0]   print(res_3)   

Output
258 16777216 1 

Explanation:

  • Big-endian unsigned short (b’\x01\x02′): The byte sequence is interpreted as a big-endian unsigned short (‘>u2’), resulting in the value 258 because 0x01 * 256 + 0x02 = 258.
  • Big-endian signed integer (b’\x01\x00\x00\x00′): The byte sequence is interpreted as a signed 4-byte integer (‘>i4’), giving the value 16777216.
  • Little-endian unsigned integer (b’\x01\x00\x00\x00′): The byte sequence is interpreted as a little-endian unsigned integer (‘<u4’), which results in 1.


Next Article
Convert Unicode to Bytes in Python

Y

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

Similar Reads

  • How to Convert Int to Bytes in Python?
    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
    2 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