2

What are nibbles in a char element?

How do we swap them?

Can anyone explain the swapping of the nibbles with an example:

Kranthi Kumar
  • 1,184
  • 3
  • 13
  • 26
  • 1
    The proposed duplicate question is a little erratic; it has answers for 16-bit and 32-bit nibble swapping — and a link to the [Bit Twiddling Hacks](http://graphics.stanford.edu/~seander/bithacks.html) which is a valuable resource. I'm not sure whether it qualifies as 'exact duplicate', though it is certainly closely related. – Jonathan Leffler Apr 13 '13 at 06:17

3 Answers3

8

The nibbles (or nybbles, by analogy with byte vs bite) are 4-bit chunks of a char.

You can swap them with:

c = ((c & 0x0F) << 4) | ((c & 0xF0) >> 4);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2
int x =  0xab; // 1010 1011 

int x1 = ( x & 0xF0) ; // 1010 0000
int x2 = ( x & 0x0F) ; // 0000 1011

x = ( x2 << 4 | x1 >> 4 ) ; // 1011 1010
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2247801
  • 145
  • 3
1
char temp1,temp2,z;// your o/p
temp1=((x & 0x0f)<<4);//x  be your input
temp2=((x & 0xf0)>>4);
z=temp1|temp2;
Santhosh Pai
  • 2,535
  • 8
  • 28
  • 49