So I got a coding problem, the the program asks me to negate every bit of a binary, for example, the regular bitwise negation will be like this: ten = 00001010 the negation is 11110101 = 245, well to achieve this, in my opinion, I can just XOR it with 255.
But the real problem is they only ask to negation only until the last '1'. My teacher teaches me to read binary from right so the last '1' if the number is ten is 2^3.
So ten = 1010 the bitwise negation is 0101 = 5
another example is
5 = 00000101 -> take only until the last '1' which is 2^2
so its like ignore this ->[00000], and only use this ->[101]
so now 5 = 101 the negation will be '010' which is equal to 2
I wonder if is there any method to help me achieve this result, at first I thought about using a loop like:
for(int i = 7; i >= 0;i--)
And store the index to a char to represent the binary and try to negate it from there, but I quickly stop when I see the constraint is 0 < n <= 1000000
How can I solve this problem?
~. As in~10. If you just want the lowest eight bits then do a bitmask with0x0ff, or assign the result touint8_tvariable.