# Swap Nibbles

• Given a 64-Bit Unsigned Integer, write a function to accept that integer as an argument and return an integer with all the nibbles swapped.
Example:
Input: 0x0123456789ABCDEF

• Welcome @pkhatri to the new Discuss! Thanks for posting this question, it looks interesting. Is this a bit-manipulation kind of problem?

• Yes. It has to be done using Bit Manipulation.

• Interesting! I have never heard of the term nibble before, until I look up on Wikipedia, which means a four-bit aggregation a.k.a. half byte.

mask1 = `0F0F0F0F0F0F0F0F`
mask2 = `F0F0F0F0F0F0F0F0`

The answer should be: `(n & mask1) << 4) | (n & mask2) >> 4)`. Does this sound right to you?

• This solution looks great!

• @1337c0d3r I came up with another way of doing it during my interview. I'll post that as soon as I get back home.

You solution is the easiest way to accomplish this. Good job :)

I believe this could be added to the Bit Manipulation section.

• @pkhatri I was wondering other ways to do it and I am looking forward to your method. Yeah will add this question to our library soon, thanks!

• ``````uint64_t p = 0x0123456789ABCDEF;

uint64_t swapped = 0x0000000000000000;

int i=0;
for(i=0;i<64;i+=8)
{
uint64_t nib1 = p & mask1>>i;
uint64_t nib2 = p & mask2>>i;

swapped |= nib1>>4;
swapped |= nib2<<4;
}
printf("%lu\n",swapped);.
``````

I put this through the phone, please edit it for code formatting if possible. Luckily I had it in my email :)

• Awesome! Thanks for sharing your solution with us @pkhatri !

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.