• C

# swapping nibble in a character

I would like to know how to swap the nibbles in a byte using bitwise operators.

Regards,
arut
###### Who is Participating?

Commented:
unsigend char x=245,swaped;

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

0

Commented:
i'm sorry, i'm not familiar with the word nibbles in this context.
please explain exactly what you mean
and give an example if you can.
0

Author Commented:
Dear rbr,

Could you please explain the anding with x part.

How does one get such expresssions easily?

When I tried it, I just couldn't proceed.Can you please suggest some rules or tricks to find solutions for problems using bit wise operators.

Regards,
arut
0

Commented:
Ok what is the representation of the high nibble:
Binary 11110000 = 0xf0

Low nibble
Binary 00001111 = 0x0f

x & 0xf0 cuts the high nibble out of the x (e.g. x=11010011 x & 0xf0 = 11010000)

x & 0xof cuts the low nibble out of the x (e.g. x=11010011 x & 0x0f = 00000011)

>> 4 shifts 4 bit to the right

11010000 >> 4 = 00001101 (you can divide through 16 will be the same results)

<< 4 shifts 4 bit to the left

00000011 << 4 = 00110000 (you can multiply with 16 will be the same results)

These 2 results will be ored (or added will be the same)
00001101 | 00110000 = 00111101 final result

without bit operations

swaped = x / 16 + (x%16) * 16;

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.