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:
Python program to Represent Negative Integers in binary format
Next article icon

Python program to print an array of bytes representing an integer

Last Updated : 24 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, the task is to write a Python program to represent the bytes of this number as an array. 

A byte is a group of 8 bits. Any integer can be represented in the form of bytes and bits. We generally use hexadecimal codes to represent a byte. A single hexadecimal character can represent 4 bits so a pair of hexadecimal characters are used to represent a byte. 

Example:

Input: N = 543

Output: [‘0x2’, ‘0x1f’]

Explanation: 543 can be represented as 1000011111 in binary which can be grouped as (10)(00011111), each group representing a byte. In hexadecimal form, this number will be (0x02)(0x1F).

Input: N = 17292567

Output: [‘0x1’, ‘0x7’, ‘0xdd’, ‘0x17’]

Explanation: 17292567 can be represented as 1000001111101110100010111 in binary which can be grouped as (1)(00000111)(11011101)(00010111), each group representing a byte. In hexadecimal form, this number will be (0x1), (0x7), (0xdd), (0x17).

Method 1 (Manual conversion):

Just like we convert decimal numbers to binary numbers, we can convert it into a base-256 number which will give us 8-bit numbers that represent bytes for the given number. 

Below is the code to implement the above-discussed method:

Python3




n = 17292567
  
# Initialize the empty array
array = []
  
# Get the hexadecimal form
while(n):
    r = n % 256
    n = n//256
    array.append(hex(r))
      
# Reverse the array to get the MSB to left
array.reverse()
print(array)
 
 
Output
['0x1', '0x7', '0xdd', '0x17']

Method 2 (Using to_bytes() method):

We can also use the to_bytes(length,byteorder) method to convert the number into a hexadecimal string. But the problem with this function is that while printing, the hex codes can convert to their corresponding characters in ASCII coding scheme. To overcome this, we can use hex() method over this method. It takes two arguments, ‘length‘ is the size of the array and ‘byteorder’ is the ordering of bytes where “big” means MSB will be on left and “little” means MSB will be on right.

Below is the code to implement the above-discussed method:

Python3




import math
  
  
n = 543
  
# Calculate the length of array
size = int(math.log(n, 256))+1
  
# Use the method to_bytes() with "big" 
# or "little" property We need to apply
# hex() method to avoid the conversion 
# into ASCII letters
hexForm = n.to_bytes(size, "big").hex()
  
# Append 8 bits together ie pair of 4 bits to get a byte
array = []
for i in range(0, len(hexForm), 2):
    array.append('0x'+hexForm[i]+hexForm[i+1])
print(array)
 
 
Output
['0x02', '0x1f']

Method 3 (Using string formatting commands):

In Python, there is a string command “%x” that can convert the given integer into hexadecimal format. We can use this to get the desired output.

Below is the code to implement the above-discussed method:

Python3




n = 8745
  
# Get string representation of hex code
hexcode = "%x" % n
  
# Pad an extra 0 is length is odd
if len(hexcode) & 1:
    hexcode = "0"+hexcode
  
array = []
for i in range(0, len(hexcode), 2):
    array.append('0x'+hexcode[i]+hexcode[i+1])
print(array)
 
 
Output
['0x22', '0x29']


Next Article
Python program to Represent Negative Integers in binary format

M

mukulbindal170299
Improve
Article Tags :
  • Python
  • Python Programs
  • binary-representation
Practice Tags :
  • python

Similar Reads

  • Python program to Represent Negative Integers in binary format
    Given a Negative Integer, the task is to write a Python program to convert the integer into binary format. Examples: Input: -14 Output: -1110 Input: -12 Output: -1100 Input: -32 Output: -100000 Let's implement this for the number in different ways : Method 1: Using format specifier 'b' In format spe
    1 min read
  • Python program to convert a byte string to a list of integers
    We have to convert a byte string to a list of integers extracts the byte values (ASCII codes) from the byte string and stores them as integers in a list. For Example, we are having a byte string s=b"Hello" we need to write a program to convert this string to list of integers so the output should be
    2 min read
  • Python program to print number of bits to store an integer and also the number in Binary format
    Given an integer, the task is to write a Python program to print the number of bits to store that integer and also print the same number in Binary format. Example: Input: n = 10 Output: Number of bits to store the number: 4 Binary value: 0b1010 Input: n = 120 Output: Number of bits to store the numb
    4 min read
  • Python Program to Convert any Positive Real Number to Binary string
    Given any Real Number greater than or equal to zero that is passed in as float, print binary representation of entered real number. Examples: Input: 123.5 Output: 1 1 1 1 0 1 1 . 1 Input: 0.25 Output: .01 Mathematical Logic along with steps done in programming: Any real number is divided into two pa
    4 min read
  • Python Program to Convert a list of multiple integers into a single integer
    There are times when we need to combine multiple integers from a list into a single integer in Python. This operation is useful where concatenating numeric values is required. In this article, we will explore efficient ways to achieve this in Python. Using join()join() method is the most efficient a
    2 min read
  • Python program to print the binary value of the numbers from 1 to N
    Given a positive number N, the task here is to print the binary value of numbers from 1 to N. For this purpose various approaches can be used. The binary representation of a number is its equivalent value using 1 and 0 only. Example for k = 15, binary value is 1 1 1 1 Method 1: Using the Elementary
    2 min read
  • Python3 Program to Rotate bits of a number
    Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. In the left rotation, the bits that fall off at the left end are put back at the right end. In the right rotation, the bits that fall off at th
    3 min read
  • Python Program for Reverse of a Number Using Type Casting
    Reversing a number is a common problem-solving exercise in programming, often used to teach the basics of algorithms and data manipulation. In Python, reversing a number can be efficiently achieved using type casting. Example: Input: 12345Output: 54321Input: -12345Output: -54321Input: 123.45Output:
    4 min read
  • Python Program to Generate Random binary string
    Given a number n, the task is to generate a random binary string of length n.Examples: Input: 7 Output: Desired length of random binary string is: 1000001 Input: 5 Output: Desired length of random binary string is: 01001 Approach Initialize an empty string, say key Generate a randomly either "0" or
    2 min read
  • Python program to print even numbers in a list
    Getting even numbers from a list in Python allows you to filter out all numbers that are divisible by 2. For example, given the list a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you might want to extract the even numbers [2, 4, 6, 8, 10]. There are various efficient methods to extract even numbers from a li
    3 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