Open In App

Bit manipulation | Swap Endianness of a number

Last Updated : 18 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: https://www.geeksforgeeks.org/little-and-big-Endian-mystery/ 
Little Endian and Big Endian are ways or storing data in machines. Some machines might use Little Endian byte ordering while others might use big Endian. This creates an inconsistency when you are transferring data from a Big Endian machine to a Little Endian machine. Usually, the compiler takes care of the conversion. But, in networking, Big Endian is used as the standard for the exchange of data between networks. Therefore, Little Endian machines need to convert their data to Big Endian while sending data through a network. Similarly, Little Endian machines need to swap the byte ordering when they receive data from a network. 
So Endianness comes into picture when you are sending and receiving data across the network from one host to another host. If the sender and receiver computer have different Endianness, then there is a need to swap the Endianness so that it is compatible.
Therefore, it is important to convert the data to little Endian or big Endian so that there is consistency and data integrity. In this article, we will look at how the Endianness of a number can be swapped. This is also a common interview question. 
 

 

Approach :

 

  1. Get the rightmost 8 bits of the number by anding it with 0x000000FF since the last 8 bits are all ones and the rest are all zeros, the result will be rightmost 8 bits of the number. The result is stored in a variable called leftmost_byte 
     
  2. Similarly, get the next 8 bits (from the right, right middle) of the number by anding it with 0x0000FF00. The result is stored in left_middle_byte
     
  3. Obtain the next 8 bits of the number by anding it with 0x00FF0000. The result is stored in right_middle_byte
     
  4. Finally, get the leftmost 8 bits of the number by anding it with 0xFF000000. The result is stored in rightmost_byte
     
  5. Now that we have all the 4 bytes of the number, we need to concatenate it in reverse order. i.e, swap the Endianness of the number. To do this, we shift the rightmost 8 bits by 24 to the left so that it becomes the leftmost 8 bits. We left shift the right middle byte by 16 (to store it as the left middle byte) We left shift the left middle byte by 8 (to store it as the right muddle byte) We finally left shift the leftmost byte by 24 to the left
     
  6. Now, we logically “or” (concatenate) all the variables to obtain the result.
     

Consider the number 0x12345678. The number is 4 bytes wide. In Big Endian, this number is represented as:
 

In Little Endian, the same number is represented as:
 

Examples: 
 

Input : 0x12345678 
Output : 0x78563412 
Input : 0x87654321 
Output : 0x21436587 
 

Implementation:
 

C++




// C++ program to print the difference
// of Alternate Nodes
#include <bits/stdc++.h>
using namespace std;
 
// Function to swap a value from
// big Endian to little Endian and
// vice versa.
int swap_Endians(int value)
{
 
    // This var holds the leftmost 8
    // bits of the output.
    int leftmost_byte;
 
    // This holds the left middle
    // 8 bits of the output
    int left_middle_byle;
 
    // This holds the right middle
    // 8 bits of the output
    int right_middle_byte;
 
    // This holds the rightmost
    // 8 bits of the output
    int rightmost_byte;
 
    // To store the result
    // after conversion
    int result;
 
    // Get the rightmost 8 bits of the number
    // by anding it 0x000000FF. since the last
    // 8 bits are all ones, the result will be the
    // rightmost 8 bits of the number. this will
    // be converted into the leftmost 8 bits for the
    // output (swapping)
    leftmost_byte = (value & 0x000000FF) >> 0;
 
    // Similarly, get the right middle and left
    // middle 8 bits which will become
    // the left_middle bits in the output
    left_middle_byle = (value & 0x0000FF00) >> 8;
 
    right_middle_byte = (value & 0x00FF0000) >> 16;
 
    // Get the leftmost 8 bits which will be the
    // rightmost 8 bits of the output
    rightmost_byte = (value & 0xFF000000) >> 24;
 
    // Left shift the 8 bits by 24
    // so that it is shifted to the
    // leftmost end
    leftmost_byte <<= 24;
 
    // Similarly, left shift by 16
    // so that it is in the left_middle
    // position. i.e, it starts at the
    // 9th bit from the left and ends at the
    // 16th bit from the left
    left_middle_byle <<= 16;
 
    right_middle_byte <<= 8;
 
    // The rightmost bit stays as it is
    // as it is in the correct position
    rightmost_byte <<= 0;
 
    // Result is the concatenation of all these values.
    result = (leftmost_byte | left_middle_byle |
              right_middle_byte | rightmost_byte);
 
    return result;
}
 
// Driver Code
int main()
{
 
    // Consider a hexadecimal value
    // given below. we are gonna convert
    // this from big Endian to little Endian
    // and vice versa.
 
    int big_Endian = 0x12345678;
    int little_Endian = 0x78563412;
 
    int result1, result2;
 
    result1 = swap_Endians(big_Endian);
 
    result2 = swap_Endians(little_Endian);
 
    printf("big Endian to little:"
           "0x%x\nlittle Endian to big: 0x%x\n",
            result1, result2);
 
    return 0;
}
 
// This code is contributed by SHUBHAMSINGH10


C




#include <stdio.h>
 
// Function to swap a value from
// big Endian to little Endian and
// vice versa.
 
int swap_Endians(int value)
{
 
    // This var holds the leftmost 8
    // bits of the output.
 
    int leftmost_byte;
 
    // This holds the left middle
    // 8 bits of the output
 
    int left_middle_byle;
 
    // This holds the right middle
    // 8 bits of the output
 
    int right_middle_byte;
 
    // This holds the rightmost
    // 8 bits of the output
 
    int rightmost_byte;
 
    // To store the result
    // after conversion
 
    int result;
 
    // Get the rightmost 8 bits of the number
    // by anding it 0x000000FF. since the last
    // 8 bits are all ones, the result will be the
    // rightmost 8 bits of the number. this will
    // be converted into the leftmost 8 bits for the
    // output (swapping)
 
    leftmost_byte = (value & 0x000000FF) >> 0;
 
    // Similarly, get the right middle and left
    // middle 8 bits which will become
    // the left_middle bits in the output
 
    left_middle_byle = (value & 0x0000FF00) >> 8;
 
    right_middle_byte = (value & 0x00FF0000) >> 16;
 
    // Get the leftmost 8 bits which will be the
    // rightmost 8 bits of the output
 
    rightmost_byte = (value & 0xFF000000) >> 24;
 
    // Left shift the 8 bits by 24
    // so that it is shifted to the
    // leftmost end
 
    leftmost_byte <<= 24;
 
    // Similarly, left shift by 16
    // so that it is in the left_middle
    // position. i.e, it starts at the
    // 9th bit from the left and ends at the
    // 16th bit from the left
 
    left_middle_byle <<= 16;
 
    right_middle_byte <<= 8;
 
    // The rightmost bit stays as it is
    // as it is in the correct position
 
    rightmost_byte <<= 0;
 
    // Result is the concatenation of all these values.
 
    result = (leftmost_byte | left_middle_byle
              | right_middle_byte | rightmost_byte);
 
    return result;
}
 
// Driver Code
int main()
{
 
    // Consider a hexadecimal value
    // given below. we are gonna convert
    // this from big Endian to little Endian
    // and vice versa.
 
    int big_Endian = 0x12345678;
    int little_Endian = 0x78563412;
 
    int result1, result2;
 
    result1 = swap_Endians(big_Endian);
 
    result2 = swap_Endians(little_Endian);
 
    printf("big Endian to little: 0x%x\nlittle Endian to big: 0x%x\n",
           result1, result2);
 
    return 0;
}


Java




// Java program to print the difference
// of Alternate Nodes
import java.util.*;
 
class GFG
{
 
// Function to swap a value from
// big Endian to little Endian and
// vice versa.
static int swap_Endians(int value)
{
 
    // This var holds the leftmost 8
    // bits of the output.
    int leftmost_byte;
 
    // This holds the left middle
    // 8 bits of the output
    int left_middle_byle;
 
    // This holds the right middle
    // 8 bits of the output
    int right_middle_byte;
 
    // This holds the rightmost
    // 8 bits of the output
    int rightmost_byte;
 
    // To store the result
    // after conversion
    int result;
 
    // Get the rightmost 8 bits of the number
    // by anding it 0x000000FF. since the last
    // 8 bits are all ones, the result will be the
    // rightmost 8 bits of the number. this will
    // be converted into the leftmost 8 bits for the
    // output (swapping)
    leftmost_byte = (value & 0x000000FF) >> 0;
 
    // Similarly, get the right middle and left
    // middle 8 bits which will become
    // the left_middle bits in the output
    left_middle_byle = (value & 0x0000FF00) >> 8;
 
    right_middle_byte = (value & 0x00FF0000) >> 16;
 
    // Get the leftmost 8 bits which will be the
    // rightmost 8 bits of the output
    rightmost_byte = (value & 0xFF000000) >> 24;
 
    // Left shift the 8 bits by 24
    // so that it is shifted to the
    // leftmost end
    leftmost_byte <<= 24;
 
    // Similarly, left shift by 16
    // so that it is in the left_middle
    // position. i.e, it starts at the
    // 9th bit from the left and ends at the
    // 16th bit from the left
    left_middle_byle <<= 16;
 
    right_middle_byte <<= 8;
 
    // The rightmost bit stays as it is
    // as it is in the correct position
    rightmost_byte <<= 0;
 
    // Result is the concatenation of all these values.
    result = (leftmost_byte | left_middle_byle |
              right_middle_byte | rightmost_byte);
 
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
    // Consider a hexadecimal value
    // given below. we are gonna convert
    // this from big Endian to little Endian
    // and vice versa.
    int big_Endian = 0x12345678;
    int little_Endian = 0x78563412;
 
    int result1, result2;
 
    result1 = swap_Endians(big_Endian);
 
    result2 = swap_Endians(little_Endian);
 
    System.out.printf("big Endian to little: 0x%x\n" +
                      "little Endian to big: 0x%x\n",
                       result1, result2);
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# Function to swap a value from
# big Endian to little Endian and
# vice versa.
def swap_Endians(value):
 
    # Get the rightmost 8 bits of the number
    # by anding it 0x000000FF. since the last
    # 8 bits are all ones, the result will be the
    # rightmost 8 bits of the number. this will
    # be converted into the leftmost 8 bits for the
    # output (swapping)
 
    leftmost_byte = (value & eval('0x000000FF')) >> 0
 
    # Similarly, get the right middle and left 
    # middle 8 bits which will become
    # the left_middle bits in the output
 
    left_middle_byle = (value & eval('0x0000FF00')) >> 8
 
    right_middle_byte = (value & eval('0x00FF0000'))>> 16
 
    # Get the leftmost 8 bits which will be the
    # rightmost 8 bits of the output
 
    rightmost_byte = (value & eval('0xFF000000'))>> 24
 
    # Left shift the 8 bits by 24
    # so that it is shifted to the
    # leftmost end
 
    leftmost_byte <<= 24
 
    # Similarly, left shift by 16
    # so that it is in the left_middle
    # position. i.e, it starts at the
    # 9th bit from the left and ends at the
    # 16th bit from the left
 
    left_middle_byle <<= 16
 
    right_middle_byte <<= 8
 
    # The rightmost bit stays as it is
    # as it is in the correct position
 
    rightmost_byte <<= 0
 
    # Result is the concatenation of all these values
 
    result = (leftmost_byte | left_middle_byle
                  | right_middle_byte | rightmost_byte)
 
 
    return result
 
 
 
# main function
if __name__ == '__main__':
 
    # Consider a hexadecimal value
    # given below. we are gonna convert
    # this from big Endian to little Endian
    # and vice versa.
    big_Endian = eval('0x12345678')
    little_Endian = eval('0x78563412')
     
    result1 = swap_Endians(big_Endian)
 
    result2 = swap_Endians(little_Endian)
 
    print("big Endian to little: % s\nlittle Endian
              to big: % s" %(hex(result1), hex(result2)))


C#




// C# program to print the difference
// of Alternate Nodes
using System;
     
class GFG
{
 
// Function to swap a value from
// big Endian to little Endian and
// vice versa.
static int swap_Endians(int value)
{
 
    // This var holds the leftmost 8
    // bits of the output.
    int leftmost_byte;
 
    // This holds the left middle
    // 8 bits of the output
    int left_middle_byle;
 
    // This holds the right middle
    // 8 bits of the output
    int right_middle_byte;
 
    // This holds the rightmost
    // 8 bits of the output
    int rightmost_byte;
 
    // To store the result
    // after conversion
    int result;
 
    // Get the rightmost 8 bits of the number
    // by anding it 0x000000FF. since the last
    // 8 bits are all ones, the result will be the
    // rightmost 8 bits of the number. this will
    // be converted into the leftmost 8 bits for the
    // output (swapping)
    leftmost_byte = (value & 0x000000FF) >> 0;
 
    // Similarly, get the right middle and left
    // middle 8 bits which will become
    // the left_middle bits in the output
    left_middle_byle = (value & 0x0000FF00) >> 8;
 
    right_middle_byte = (value & 0x00FF0000) >> 16;
 
    // Get the leftmost 8 bits which will be the
    // rightmost 8 bits of the output
    rightmost_byte = (int)(value & 0xFF000000) >> 24;
 
    // Left shift the 8 bits by 24
    // so that it is shifted to the
    // leftmost end
    leftmost_byte <<= 24;
 
    // Similarly, left shift by 16
    // so that it is in the left_middle
    // position. i.e, it starts at the
    // 9th bit from the left and ends at the
    // 16th bit from the left
    left_middle_byle <<= 16;
 
    right_middle_byte <<= 8;
 
    // The rightmost bit stays as it is
    // as it is in the correct position
    rightmost_byte <<= 0;
 
    // Result is the concatenation of all these values.
    result = (leftmost_byte | left_middle_byle |
              right_middle_byte | rightmost_byte);
 
    return result;
}
 
// Driver Code
public static void Main(String[] args)
{
    // Consider a hexadecimal value
    // given below. we are gonna convert
    // this from big Endian to little Endian
    // and vice versa.
    int big_Endian = 0x12345678;
    int little_Endian = 0x78563412;
 
    int result1, result2;
 
    result1 = swap_Endians(big_Endian);
 
    result2 = swap_Endians(little_Endian);
 
    Console.Write("big Endian to little: 0x{0:x}\n" +
                    "little Endian to big: 0x{1:x}\n",
                                   result1, result2);
}
}
 
// This code is contributed by Rajput-Ji


Javascript




// Function to convert integer to Hex
var Hex = function (rgb) {
  var hex = Number(rgb).toString(16);
  if (hex.length < 2) {
       hex = "0" + hex;
  }
  return hex;
};
 
 
// Function to swap a value from
// big Endian to little Endian and
// vice versa.
function swap_Endians(value){
     
    // Get the rightmost 8 bits of the number
    // by anding it 0x000000FF. since the last
    // 8 bits are all ones, the result will be the
    // rightmost 8 bits of the number. this will
    // be converted into the leftmost 8 bits for the
    // output (swapping)
    leftmost_byte = (value & eval('0x000000FF')) >> 0;
     
    // Similarly, get the right middle and left
    // middle 8 bits which will become
    // the left_middle bits in the output
    left_middle_byle = (value & eval('0x0000FF00')) >> 8;
     
     right_middle_byte = (value & eval('0x00FF0000'))>> 16
 
    // # Get the leftmost 8 bits which will be the
    // # rightmost 8 bits of the output
 
    rightmost_byte = (value & eval('0xFF000000'))>> 24
     
     
    // Left shift the 8 bits by 24
    // so that it is shifted to the
    // leftmost end
  
    leftmost_byte <<= 24
 
    // # Similarly, left shift by 16
    // # so that it is in the left_middle
    // # position. i.e, it starts at the
    // # 9th bit from the left and ends at the
    // # 16th bit from the left
 
    left_middle_byle <<= 16
 
    right_middle_byte <<= 8
 
    // # The rightmost bit stays as it is
    // # as it is in the correct position
 
    rightmost_byte <<= 0
 
    // # Result is the concatenation of all these values
 
    result = (leftmost_byte | left_middle_byle | right_middle_byte | rightmost_byte)
 
 
    return result
}
 
// Consider a hexadecimal value
// given below. we are gonna convert
// this from big Endian to little Endian
// and vice versa.
let big_Endian = eval('0x12345678')
let little_Endian = eval('0x78563412')
     
let result1 = swap_Endians(big_Endian)
 
let result2 = swap_Endians(little_Endian)
 
console.log("big Endian to little:0x" + Hex(result1));
console.log("\nlittle Endian to big: 0x" + Hex(result2));


Output

big Endian to little:0x78563412
little Endian to big: 0x12345678

Approach#2: Using struct

Another way to swap the endianness of a number is by using the struct module in Python. 

Algorithm

1. Define a function named swap_endianness that takes a number num as input.
2. Use the struct.pack method to pack the number as a 32-bit integer in network byte order (big-endian).
3. Store the packed number in the variable packed_num.
4. Use the struct.unpack method to unpack the number as a 32-bit integer in little-endian byte order.
5. Store the unpacked number in the variable unpacked_num.
6. Return the unpacked number.
7. Define two variables num1 and num2 with hexadecimal values.
8. Call the swap_endianness function with num1 as the input, and print the result as a hexadecimal value.
9. Call the swap_endianness function with num2 as the input, and print the result as a hexadecimal value.

Python3




import struct
 
def swap_endianness(num):
    # Pack the number as a 32-bit integer in network byte order
    packed_num = struct.pack('>I', num)
    # Unpack the number as a 32-bit integer in little-endian byte order
    unpacked_num = struct.unpack('<I', packed_num)[0]
    return unpacked_num
 
num1 = 0x12345678
num2 = 0x87654321
 
print(hex(swap_endianness(num1))) # Output: 0x78563412
print(hex(swap_endianness(num2))) # Output: 0x21436587


Output

0x78563412
0x21436587

Time Complexity: O(1)

Space Complexity: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads