×

Python Struct

Python

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way. The python language can also be used in web development; Django and Flask are the frameworks used to create web applications using Python. In Python, indentation is the main concept; if we do not follow proper indentation, the code may not run. We can easily create an application in Python if we are familiar with indentation, Variables, Operators, loop concepts and function concepts in python language. The python programming language has pre-installed modules, which help perform various operations, and one of the modules is the struct module.

Struct Module in Python

The struct module is available in the python programming language; this module helps convert the Python values and the C structs; these Cstructs are represented as the python bytes objects.

This module helps handle the binary data stored in the files. The Format strings are the mechanism used to specify the expected layout when packing and unpacking the data. The struct module is available in Python 3. x, so for running the code, we need to use the Python3 interpreter, and it is not available in Python 2. x so that we can run the code in other interpreters rather than Python 3.

Struct Functions

There are many built-in functions available in the struct module. The struct function takes the buffer argument, the objects in the module use the buffer protocol, and in return, it will provide us with the readable or read-writeable buffer. The most commonly used types for this buffer protocol are the bytes and bytearray. Other types are viewed as the array of bytes that will implement the buffer protocol so that this data can be read without additional copying from the bytes object.

 Now let us look at some of the built-in functions available in the struct module:

1. struct.pack( ):

This method or function will return the string containing the values a1,a2,a3,a4…. these values are packed according to the given format; the Format strings is a mechanism used to specify the expected layout when the packing and the unpacking of the data are done. We need to follow the format used by the Format strings; otherwise, it will raise the struct.error

Syntax:

Struct.pack( format,   a1, a2, a3 ,……)

Parameters:

  • Format: This is the format used to format the given data into the required format.
  • a1, a2, a3…: These are the values provided to the function that must be formatted.

Code:

# importing the library
importstruct
# Format: d is short in C type
# Format: a is int in C type
#Format: ‘daa', which stands for 'short intint.'


data = struct.pack(‘daa’, 1, 2, 3)
print( data )


# Format: j is long in C type
# Format: ‘jjj’ stands for ‘ longlonglong ‘


data  =struct.pack(‘jjj’, 1,2,3)
print(data)

Output:

b’\x01\x00\x02\x00\x00\x01\x02\x02\x00\x01\x00\x00\x01\x02\x00\x01\x01\x00’
b’\x01\x00\x01\x00\x02\x00\x01\x02\x01\x02\x01\x03\x01\x01\x01\x00\x01\x01’

2. Struct.unpack( ):

This method or function will return the unpacked values a1, a2, a3, a4…. these values are packed according to the format; the Format strings are a mechanism used to specify the expected layout when the packing and the unpacking of the data are done. These values are returned as a tuple whose size equals the total number of values passed to the struct.pack( ) during the packing.

Syntax:

Struct.unpack(format,  string)

Parameters:

  • Format: This is the format used to format the given data into the required format.
  • String: This string will contain unpacked values using the unpack( ) function.

Code:

# importing the library
importstruct
# Format: d is short in C type
# Format: a is int in C type
#Format: ‘daa', which stands for 'short intint.'


data = struct.pack(‘daa’, True, 1, 2, 3)
print( data )


# Using the struct.unpack( ) function
# The variables a1,a2,a3,….  these values are returned as the elements in the tuple
struct.unpack(‘data, data)
tup)

Output:

b’\x01\x00\x02\x00\x00\x01\x02\x02\x00\x01\x00\x00\x01\x02\x00\x01\x01\x00’
(True, 1, 2, 3)
b’\x01\x00\x02\x00\x00\x01\x02\x02\x00\x01’
(1, 3.6567)

Here the ‘b’ stands for the binary output. We can observe that the output is returned the values in the form of a tuple as we used the unpack( ) function.


Related Topics

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Python Dictionary Methods

Python Dictionary Methods Python has a set of built-in methods that dictionary objects can call. All the python dictionary methods are as follow: Methods Description clear() The dictionary.clear() method removes all the elements...

3 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

3 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.