This question has already been answered:

I ask for help with the task in the title!

Reported as a duplicate by the participants αλΡχολυτ , Vlad from Moscow , Harry , Abyx c ++ Nov 11 '16 at 22:19 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • What is the problem then? Show that you did not work. - pavel
  • @droppenheimer It’s not clear exactly what needs to be done. Could you give an example? - Vlad from Moscow
  • A number is entered from the keyboard, I translate it into a binary system, then I shift it to position p. I need to invert - I do, but I don’t know how to do it with certain bits. - droppenheimer
  • @droppenheimer Once again: can you give an example of what you want to get ?! - Vlad from Moscow
  • Example: The number is 27. 11011. I want to invert from position 2 (the fourth number in this case). That is, it should be something like: 00101 - droppenheimer

2 answers 2

Prepare the mask - the bits in the inversion positions are single, in the others - zero. Perform a bitwise XOR operation ( ^ ).

I hope to create such a mask will not be?

  • So the whole problem in this very mask, how to apply it is understandable, but here’s how to make up ... - droppenheimer
 unsigned a = 12345; unsigned p = 10; // позиция, нумСрация с 0 ΠΎΡ‚ ΠΌΠ»Π°Π΄ΡˆΠΈΡ… Π±ΠΈΡ‚ΠΎΠ² ΠΊ ΡΡ‚Π°Ρ€ΡˆΠΈΠΌ unsigned n = 2; // количСство Π±ΠΈΡ‚ΠΎΠ² для инвСртирования // БоставляСм маску unsigned mask = (1u << n) - 1; // 'n' Π΅Π΄ΠΈΠ½ΠΈΡ† Π² ΠΌΠ»Π°Π΄ΡˆΠΈΡ… разрядах mask <<= p; // 'n' Π΅Π΄ΠΈΠ½ΠΈΡ† Π²Π»Π΅Π²ΠΎ ΠΎΡ‚ ΠΏΠΎΠ·ΠΈΡ†ΠΈΠΈ 'p' // Π˜Π½Π²Π΅Ρ€Ρ‚ΠΈΡ€ΡƒΠ΅ΠΌ Π±ΠΈΡ‚Ρ‹ a ^= mask;