Swap Nibbles

  • 0

    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.
    Input: 0x0123456789ABCDEF
    Output: 0x1032547698BADCFE

  • 0

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

  • 0

    Yes. It has to be done using Bit Manipulation.

  • 0

    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.

  • 2

    How about creating two bitmasks?

    mask1 = 0F0F0F0F0F0F0F0F
    mask2 = F0F0F0F0F0F0F0F0

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

  • 0

    This solution looks great!

  • 0

    @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.

  • 0

    @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!

  • 0
    uint64_t p = 0x0123456789ABCDEF;
    uint64_t swapped = 0x0000000000000000;
    uint64_t mask1 = 0xF000000000000000;
    uint64_t mask2 = 0x0F00000000000000;
    int i=0;
    	uint64_t nib1 = p & mask1>>i;
    	uint64_t nib2 = p & mask2>>i;
    	swapped |= nib1>>4;
    	swapped |= nib2<<4;

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

  • 1

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

Log in to reply

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