2

How can I switch the certain bits of a number? For example, given bit representation (just an example, the syntax is surely wrong!):

someNumber = 00110111
changeNumber = 11100110

Then how can I change the far right bit of someNumber with the far right bit of the changeNumber without changing the rest bits of the someNumber? So the result would be:

00110111   //someNumber
11100110   //changeNumber
________
00110110
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Have you looked at the bit shifting operator? http://stackoverflow.com/questions/141525/what-are-bitwise-shift-bit-shift-operators-and-how-do-they-work – Tdorno Nov 15 '15 at 03:46

4 Answers4

3

Extract the far right bit of changeNumber:

changeNumber & 1

Remove the far right bit of someNumber:

someNumber & ~1

And OR them together:

 (changeNumber & 1) | (someNumber & ~1)

To set bit n, change 1 to 2n.

orlp
  • 112,504
  • 36
  • 218
  • 315
1

I suggest the following steps:

  1. Clear the last bit of someNumber.

    someNumber &= ~1
    
  2. Extract the last bit of changeNumber

    int lastBit = changeNumber & 1;
    
  3. Set the last bit of someNumber:

    someNumber |= lastBit;
    
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

One a similar line as Martin,

Test the last bit of someNumber, and use the result to select the operation to change some number ('bitwise and' or 'bitwise or')

#DEFINE SWITCH_MASK_OR 0b00000001
#DEFINE SWITCH_MASK_AND (~SWITCH_MASK_OR)
...
result = changeNumber & SWITCH_MASK_OR ? \
         someNumber | SWITCH_MASK_OR : someNumber & SWITCH_MASK_AND;
jih
  • 19
  • 1
0

AND the changenumber with a mask of 00000001, so extracting the state of the lowest bit, all others set to 0: 00000000

AND the somenumber with a mask of 11111110, so setting the lowest bit to 0 while leaving the rest unchanged: 00110110

OR the two results together, so : 00110110

Martin James
  • 24,453
  • 3
  • 36
  • 60