user656521
user656521

Reputation:

How to swap nibbles in C?

How to swap the nibble bit positions of a number?

For example: 534, convert it into binary, the rightmost 4 bits has to be interchanged with the leftmost 4 bits and then make a new number with that.

Anyone know how to do this?

Upvotes: 3

Views: 18669

Answers (5)

Nagesh Jamakhandi
Nagesh Jamakhandi

Reputation: 1

 input :  data=0x12345678; swap nibbles 0 and 3.
output : data=0x12348675.

   nib1 = (data>>(0*4)) & 0xF;     //nib1 = 0x08
   nib1 = nib1<<(3*4);             //nib1 = 0x8000

   nib2 = (data>>(3*4)) & 0xF;     //nib2 = 0x05
   nib2 = nib2<<(0*4);             //nib2 = 0x5
             
   data = data & ~(0xF<<(0*4));    //data = 0x12345670
   data = data & ~(0xf<<(3*4));    //data = 0x12340670

   data |= nib1 | nib2;            //data = 0x12348675
            

Upvotes: 0

Alok Pindoriya
Alok Pindoriya

Reputation: 1

//program to swap nibbles from 32 bit number swap
#include <stdio.h>
#include <stdint.h>

int main()
{
 uint32_t n = 0x10203040;
 uint32_t swaped_no=0;
 int data;
 char shift = 0;
 for(int i =0;i<4;i++)
 {
  data= n>>shift;
  data = (((data & 0x0F)<<4) | ((data & 0xF0)>>4));
  swaped_no = swaped_no | (data<<shift);
  shift=shift+8;
 }
 printf("swapped no 0x%08x",swaped_no);
}

swapped no 0x01020304

Upvotes: 0

kapilddit
kapilddit

Reputation: 1769

1)

y = ((x >> 4) & 0x0f) | ((x << 4) & 0xf0);

2)

unsigned char swap_nibbles(unsigned char c)
{
     unsigned char temp1, temp2;

     temp1 = c & 0x0F;
     temp2 = c & 0xF0;
     temp1=temp1 << 4;
     temp2=temp2 >> 4;

     return(temp2|temp1); //adding the bits
}

3)

unsigned char nibbleSwap(unsigned char a)
{
    return (a<<4) | (a>>4);
}

Upvotes: 4

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84189

Start from the fact that hexadecimal 0xf covers exactly four bits. There are four nibbles in a 16-bit number. The masks for the nibbles are 0xf000, 0xf00, 0xf0, and 0xf. Then start masking, shifting and bitwise OR-ing.

Upvotes: 4

sarnold
sarnold

Reputation: 104080

Sean Anderson's bit twiddling guide has the following:

// swap nibbles ... 
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);

under the entry for Reverse an N-bit quantity in parallel in 5 * lg(N) operations.

Upvotes: 5

Related Questions