Let's say I have a binary number like: 0101010101. Now I want to negate only the 1st 5th and 8th digit to change it to 1101110001. Is there an algorithm to do this? If so, how does it work?
Asked
Active
Viewed 56 times
-1
-
@OliverCharlesworth Very possibly, didn't really know what to search for , thanks :) – Noé Corneille Jul 21 '15 at 22:41
1 Answers
0
Some pseuocode..
function negateDigit(num, digit)
if num >> digit & 1 then
return num ^ (pow(2, digit))
else
return num + pow(2, digit)
end
end
Basically what this is doing>
It bit shifts all the way untill the specified digit is the first digit is the specified digit desired
It than ands the number by 1 (removing any greater digits)
After that, if the digit exists (this is lua btw), than it XORs the digit out of the system (i suppose you could just subtract it too..)
Else, it adds it back in
E/ as the comment to OP showed, I overcomplicated it by adding the check, you can just use the XOR operation regardless of the flip state.
function negateDigit(num, digit)
return num ^ (1 << digit)
end

Arhowk
- 901
- 4
- 11
- 22