I am coding in C programming. Let's say I have a character: char letter=0x0000; So the binary data for the letter is now "00000000" let say I want change the binary data to "10000000" and later to change it "10010000", is there a bitwise operator or method that would allow me to change a "0" to a "1" or "1" to a "0" at a specific position. Also is this possible?
-
1Yes it is possible, there are bitwise operators in C.wildplasser– wildplasser2013-10-26 18:22:31 +00:00Commented Oct 26, 2013 at 18:22
-
Can you show me the bitwise operator that would be used to go from "00000000" to "00100000" (change "0" at position 2 to "1")?user2106253– user21062532013-10-26 18:25:47 +00:00Commented Oct 26, 2013 at 18:25
-
bit.ly/1andHfTCharlie Burns– Charlie Burns2013-10-26 18:27:08 +00:00Commented Oct 26, 2013 at 18:27
-
Check the ans. by templatetypedefArpit– Arpit2013-10-26 18:27:52 +00:00Commented Oct 26, 2013 at 18:27
-
That is not position 2. Bits are usually counted from right to left, starting with zero, so it would be bit 5.wildplasser– wildplasser2013-10-26 18:28:08 +00:00Commented Oct 26, 2013 at 18:28
3 Answers
If you XOR any bit with a 1 bit, it toggles its value:
0 ^ 1 = 1
1 ^ 1 = 0
Similarly, if you XOR any bit with 0, it keeps the same value:
0 ^ 0 = 0
1 ^ 0 = 1
Therefore, you can flip the nth bit of a number by XORing it with a number that has zero bits everywhere except in bit n:
val ^= (1 << n);
Hope this helps!
5 Comments
1 ^ 1 is 0, not 1.Yes it is very much possible. Just use bitwise exclusive OR or simply XOR operator on the number with 2 to the power of n where as n is the digit you want to change. ^ is the XOR operator in C.
000000 (decimal 0)
^ 100000 (decimal 32 = 2 power 5 = 1 << 5)
= 100000
1010 (decimal 10)
XOR 0010 (decimal 2 = 2 power 1 = 1 << 1)
= 1000
You can calculate 2 to the power of n by simply shifting bits in 1 by n bits. So 2 to the power of 4 can be obtained by shifting bits in 1 by 4 places.
inputNum ^ (1 << n) will give what you needed if toggling is all you need.
Bitwise XOR "^"
bit a bit b a ^ b (a XOR b)
0 0 0
0 1 1
1 0 1
1 1 0
However remember that doing XOR on a bit that already has 1 will convert it to zero. because 1 ^ 1 = 0;
If you just want to convert 0 to 1 and keep 1 if it is already there. You can have to use bitwise Or operator.
Bitwise OR "|"
bit a bit b a | b (a OR b)
0 0 0
0 1 1
1 0 1
1 1 1
Following is an example
11001110
| 10011000
= 11011110
Source: http://en.wikipedia.org/wiki/Bitwise_operations_in_C & http://en.wikipedia.org/wiki/Bitwise_operation
Comments
You can use bitwise AND (&) and OR (|) operator. For example:
01001000 | 10111000 = 11111000
This is done following: 72 | 184 = 248
(72 = 64+8)
For details see following tutorial: http://www.cprogramming.com/tutorial/bitwise_operators.html