Tuesday, July 14, 2009

How to do an increment operation in C ( i++) using bitwise operators ?

Easy but pointless, therefore this must be a homework question! nevertheless here goes.. Use the XOR and SHIFT operators. Also, it is assumed that when using the XOR operator that the result is placed in the first operand, i.e, b=b XOR c





Example pseudo code adding 00000001 (1) to 10110011(179).





Variables:





a=10110011 ( Original number and will also contain final result )


b ( temp variable )


c ( temp variable )





Routine:





1) b=a


2) c=00000001


3) b XOR c


4) IF b%26gt;a, THEN a=b, EXIT


5) a=b


6) SHIFTLEFT c


7) GOTO 3)





Basically all that is happening is that working from right to left, you are removing any '1's from the original number until you find a '0' which you then change to a '1'.


NOTE: you will have to check that you are looping no more than the number of bits in the number otherwise if a==11111111, it will be reset to zero and you will end up in an infinite loop! ;o)

How to do an increment operation in C ( i++) using bitwise operators ?
You don't. The increment operator is used to increment a number in c++.





Bitwise operators are used for bitwise operations.
Reply:This sounds like a homework problem - as noone would want to do this otherwise.





You will have to implement a 2 bit addition function with carry and then repeat and shift for 32 bits, if you are using 32-bit integers.
Reply:seems like a pretty silly task. the compiler optimizes the increment operator.





you use a barrel shifter i suppose. you would only need to use the '%26lt;%26lt;' and '%26amp;'.


No comments:

Post a Comment