Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to swap pairs of bits of unsigned int in C

This is the code I have so far? But its not working..

uint64_t bit_swap(uint64_t value) {
    return ((value & 0xAAAAAAAA) >> 1) |
            ((value & 0x55555555) << 1);   
}

bit_swap(0x1111111111111111) should return 0x2222222222222222 but is returning 0x0000000022222222 instead

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

value & 0xAAAAAAAA

That is equivalent to : value & 0x00000000AAAAAAAA

And since we know that anything anded with 0 will give 0 hence the top 32 bits will always be 0. Change to:

return ((value & 0xAAAAAAAAAAAAAAAA) >> 1) |
        ((value & 0x5555555555555555) << 1);  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading