Open In App

Swap two nibbles in a byte

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A nibble is a four-bit aggregation or half an octet. There are two nibbles in a byte. 
Given a byte, swap the two nibbles in it. For example, 100 is represented as 01100100 in a byte (or 8 bits). The two nibbles are (0110) and (0100). If we swap the two nibbles, we get 01000110 which is 70 in decimal.

Method 1: To swap the nibbles, we can use bitwise &, bitwise ” operators. A byte can be represented using an unsigned char in C as size of char is 1 byte in a typical C compiler. 

Below is the implementation of the above idea. 

C++
// C++ program to swap two
// nibbles in a byte
#include <bits/stdc++.h>
using namespace std;

int swapNibbles(int x)
{
    return ( (x & 0x0F) << 4 | (x & 0xF0) >> 4 );
}

// Driver code
int main()
{
    int x = 100;
    cout << swapNibbles(x);
    return 0;
}

//This code is contributed by Shivi_Aggarwal
C
#include <stdio.h>

unsigned char swapNibbles(unsigned char x)
{
    return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 );
}

int main()
{
    unsigned char x = 100;
    printf("%u", swapNibbles(x));
    return 0;
}
Java
// Java program to swap two
// nibbles in a byte

class GFG {
    
static int swapNibbles(int x)
{
    return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);
}

// Driver code
public static void main(String arg[])
{
    int x = 100;
    System.out.print(swapNibbles(x));
}
}

// This code is contributed by Anant Agarwal.
Python3
# python program Swap
# two nibbles in a byte

def swapNibbles(x):
    return ( (x & 0x0F)<<4 | (x & 0xF0)>>4 )

# Driver code

x = 100
print(swapNibbles(x))

# This code is contributed
# by Anant Agarwal.
C#
// C# program to swap two
// nibbles in a byte
using System;

class GFG {

// Function for swapping    
static int swapNibbles(int x)
{
    return ((x & 0x0F) << 4 | 
            (x & 0xF0) >> 4);
}

// Driver code
public static void Main()
{
    int x = 100;
    Console.Write(swapNibbles(x));
}
}

// This code is contributed by Nitin Mittal.
Javascript
<script>
// javascript program to swap two
// nibbles in a byte   
function swapNibbles(x)
{
    return ((x & 0x0F) << 4 | (x & 0xF0) >> 4);
}

// Driver code
var x = 100;
document.write(swapNibbles(x));

// This code is contributed by Princi Singh 
</script>
PHP
<?php
// PHP program to swap two
// nibbles in a byte

// function to Swap two nibbles
// in a byte in php program
function swapNibbles($x)
{
    return ( ($x & 0x0F) << 4 | 
           ($x & 0xF0) >> 4 );
}

    // Driver Code
    $x = 100;
    echo swapNibbles($x);

// This Code is Contributed by Ajit
?>

Output
70

Time Complexity: O(1)
Auxiliary Space: O(1)


Explanation: 
100 is 01100100 in binary. The operation can be split mainly in two parts 
1) The expression “x & 0x0F” gives us last 4 bits of x. For x = 100, the result is 00000100. Using bitwise ‘<<‘ operator, we shift the last four bits to the left 4 times and make the new last four bits as 0. The result after shift is 01000000.
2) The expression “x & 0xF0” gives us first four bits of x. For x = 100, the result is 01100000. Using bitwise ‘>>’ operator, we shift the digit to the right 4 times and make the first four bits as 0. The result after shift is 00000110.
At the end we use the bitwise OR ‘|’ operation of the two expressions explained above. The OR operator places first nibble to the end and last nibble to first. For x = 100, the value of (01000000) OR (00000110) gives the result 01000110 which is equal to 70 in decimal.
/p>

Another Approach:

Using binary instead of hexadecimal values. It is much clearer to beginners.

  • Take & of 00001111 with number to get right nibble i.e. 0b00001111 & N
  • ake & of 11110000 with number to get left nibble i.e. 0b11110000 & N
  • Left shift the right nibble obtained in step 1 by 4 positions to get it as left nibble in the final answer i.e. <<4
  • Right shift the left nibble obtained in step 2 by 4 positions to get it as right nibble in final answer >>4
  • Do or( | ) operation between values obtained in step 3 & 4 to get the answer

Below is the implementation of the above approach:

C++
// C++ program to swap two
// nibbles in a byte
#include <bits/stdc++.h>
using namespace std;

 int swapNibbles(int N) {
      // Step 1
        int right = (N & 0b00001111);
      // Step 3
        right= (right<<4);
      // Step 2
        int left = (N & 0b11110000);
      // Step 4
        left = (left>>4);
      // Step 5
        return (right | left);
    }

// Driver code
int main()
{
    int n = 100;
    cout << "Original: " << n << " Swapped: " << swapNibbles(n);
        
    return 0;
}

// This code is contributed by sanjoy_62.
Java
/*package whatever //do not write package name here */

import java.io.*;
class Solution{
    static int swapNibbles(int N) {
      // Step 1
        int right = (N & 0b00001111);
      // Step 3
        right= (right<<4);
      // Step 2
        int left = (N & 0b11110000);
      // Step 4
        left = (left>>4);
      // Step 5
        return (right | left);
    }
}
class GFG {
    public static void main (String[] args) {
      Solution s = new Solution();
      int n = 100;
        System.out.println("Original: "+ n + " Swapped: " + s.swapNibbles(n));
    }
}
Python3
# Python code for the above approach
from math import ceil, sqrt

def swapNibbles(N) :
    
    # Step 1
    right = (N & 0b00001111)
    
    # Step 3
    right= (right<<4)
    
    # Step 2
    left = (N & 0b11110000)
      
    # Step 4
    left = (left>>4)
    
    # Step 5
    return (right | left)

# Driver Code
n = 100;
print("Original: ", n, end = " ")
print(" Swapped: " , swapNibbles(n))

# This code is contributed by code_hunt.
C#
// C# program to swap two
// nibbles in a byte
using System;

public class GFG{

  static int swapNibbles(int N) {
    // Step 1
    int right = (N & 0b00001111);
    // Step 3
    right= (right<<4);
    // Step 2
    int left = (N & 0b11110000);
    // Step 4
    left = (left>>4);
    // Step 5
    return (right | left);
  }

  // Driver Code
  static public void Main (){
    int n = 100;
    Console.Write("Original: "+ n + " Swapped: " + swapNibbles(n));
  }
}

// This code is contributed by shruti456rawal
Javascript
// JavaScript code for the above approach
function swapNibbles(N)
{
    
    // Step 1
    var right = (N & 0b00001111);
    
    // Step 3
    var right= (right<<4);
    
    // Step 2
    var left = (N & 0b11110000);
      
    // Step 4
    var left = (left>>4);
    
    // Step 5
    return (right | left);

}

// Driver Code
var n = 100;
console.log("Original:", n, " Swapped:", swapNibbles(n));

// This code is contributed by phasing17

Output
Original: 100 Swapped: 70

Time Complexity: O(1)
Auxiliary Space: O(1)

Method 3: Without BIT Manipulation

This approach extracts the first 4 bits of number by dividing it by 16 and extracts last 4 bits as remainder of N with 16. These two different nibbles are computed by swapping and adding to return the answer as below.

C++
// C++ program to swap two
// nibbles in a byte by flutterfly
#include <bits/stdc++.h>
using namespace std;

int swapNibbles(int x)
{
    int a = x % 16; // Extract the last 4 bits (nibble) of N
    int b = x / 16; // Extract the first 4 bits (nibble) of N
    int ans = a * 16 + b; // Swap the two nibbles and form the resulting number
    return ans; // Return the resulting number
}

// Driver code
int main()
{
    int x = 100;
    cout << swapNibbles(x);
    return 0;
}
Java
// Java program to swap two
// nibbles in a byte by flutterfly

class GFG {
    
static int swapNibbles(int x)
{
    int a = x % 16; // Extract the last 4 bits (nibble) of N
    int b = x / 16; // Extract the first 4 bits (nibble) of N
    int ans = a * 16 + b; // Swap the two nibbles and form the resulting number
    return ans; // Return the resulting number
}

// Driver code
public static void main(String arg[])
{
    int x = 100;
    System.out.print(swapNibbles(x));
}
}
Python3
# Python program to swap two
# nibbles in a byte by flutterfly
def swapNibbles(x):
    a = x % 16  # Extract the last 4 bits (nibble) of N
    b = x // 16  # Extract the first 4 bits (nibble) of N
    ans = a * 16 + b  # Swap the two nibbles and form the resulting number
    return ans  # Return the resulting number

# Driver code
x = 100
print(swapNibbles(x))
JavaScript
// Javascript program to swap two
// nibbles in a byte by flutterfly

function swapNibbles(x) {
    let a = x % 16; // Extract the last 4 bits (nibble) of N
    let b = Math.floor(x / 16); // Extract the first 4 bits (nibble) of N
    let ans = a * 16 + b; // Swap the two nibbles and form the resulting number
    return ans; // Return the resulting number
}

// Driver code
let x = 100;
console.log(swapNibbles(x));

Output

70

Time Complexity: O(1)

Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads