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