Manipulación de bits | Intercambiar Endianness de un número

Requisito previo: https://www.geeksforgeeks.org/little-and-big-Endian-mystery/ 
Little Endian y Big Endian son formas de almacenar datos en máquinas. Algunas máquinas pueden usar el ordenamiento de bytes Little Endian mientras que otras pueden usar Big Endian. Esto crea una incoherencia cuando se transfieren datos de una máquina Big Endian a una máquina Little Endian. Por lo general, el compilador se encarga de la conversión. Pero, en redes, Big Endian se utiliza como estándar para el intercambio de datos entre redes. Por lo tanto, las máquinas Little Endian necesitan convertir sus datos a Big Endian mientras envían datos a través de una red. De manera similar, las máquinas Little Endian necesitan intercambiar el orden de los bytes cuando reciben datos de una red. 
Entonces Endianness entra en escena cuando envía y recibe datos a través de la red de un host a otro host. Si la computadora del remitente y el receptor tienen un Endianness diferente, entonces es necesario intercambiar el Endianness para que sea compatible.
Por lo tanto, es importante convertir los datos a Little Endian o Big Endian para que haya consistencia e integridad de datos. En este artículo, veremos cómo se puede intercambiar el Endianness de un número. Esta es también una pregunta común en las entrevistas. 
 

Acercarse :

  1. Obtenga los 8 bits más a la derecha del número añadiéndolo con 0x000000FF ya que los últimos 8 bits son todos unos y el resto son todos ceros, el resultado serán los 8 bits más a la derecha del número. El resultado se almacena en una variable llamada leftmost_byte 
     
  2. Del mismo modo, obtenga los siguientes 8 bits (desde la derecha, en el medio derecho) del número añadiéndolo con 0x0000FF00. El resultado se almacena en left_middle_byte
     
  3. Obtenga los siguientes 8 bits del número añadiéndolo con 0x00FF0000. El resultado se almacena en right_middle_byte
     
  4. Finalmente, obtenga los 8 bits más a la izquierda del número añadiéndolo con 0xFF000000. El resultado se almacena en rightmost_byte
     
  5. Ahora que tenemos los 4 bytes del número, necesitamos concatenarlo en orden inverso. es decir, intercambiar el Endianness del número. Para hacer esto, desplazamos los 8 bits más a la derecha por 24 hacia la izquierda para que se conviertan en los 8 bits más a la izquierda. Desplazamos a la izquierda el byte medio derecho 16 (para almacenarlo como el byte medio izquierdo) Desplazamos a la izquierda el byte medio izquierdo 8 (para almacenarlo como el byte confuso derecho) Finalmente desplazamos a la izquierda el byte más a la izquierda 24 a la izquierda
     
  6. Ahora, lógicamente “o” (concatenamos) todas las variables para obtener el resultado.
     

Considere el número 0x12345678. El número tiene 4 bytes de ancho. En Big Endian , este número se representa como:
 

En Little Endian , el mismo número se representa como:
 

Ejemplos: 
 

Entrada: 0x12345678 
Salida: 0x78563412 
Entrada: 0x87654321 
Salida: 0x21436587 
 

Implementación :
 

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));
Producción

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

Publicación traducida automáticamente

Artículo escrito por Adith Bharadwaj y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *