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 can I flip n number of bits in a number in assembly?

How can I flip "n" number of lower/higher bits in a number using the xor operation in assembly?

How would the mask be calculated? For example, if n=2 for "1110" the mask would be "1100" for higher 2 and "0011" for lower two, however for "111111" it would be "110000" for higher two, and "000011" for lower two. So what is the correlation between n=2 and those masks? How can I create them just based on the number of bits that need to be flipped and not based on the actual number that’s being flipped? (supposing that we don’t know the number beforehand) Thank you in advance!

I tried finding the number of bits the number I am working with has, and I believe have managed to do so but still can’t find the correlation.

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 :

I think that given the number of bits in the number you can determine what the mask you should be by using bit shift operations. For example, if you want to flip the lowest n bits you could do something like

mask = (1 << n) - 1;
value = value ^ mask;

If you want to flip the highest n bits you would need to do something like

mask = ((1<<(n))-1) << (number of bits - n);
value = value ^ mask;
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