Bitwise XOR

Bitwise XOR for resetting a variable

Page 1 of 1

4 Replies - 5393 Views - Last Post: 14 September 2006 - 07:15 AM Rate Topic: -----

#1 mrgubbala  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-September 06

Bitwise XOR

Posted 13 September 2006 - 11:52 PM

int counter=0;

if(counter < 10)
counter++;
else
counter=0;

The above code, resets the value to O after reaching 10.
How can we achieve the same using just Bitwise XOR without
"if".

Thanks!
Is This A Good Question/Topic? 0
  • +

Replies To: Bitwise XOR

#2 Xing  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 19
  • View blog
  • Posts: 725
  • Joined: 22-July 06

Re: Bitwise XOR

Posted 14 September 2006 - 12:18 AM

Xoring the value with itself reset's the value to 0.
Was This Post Helpful? 0
  • +
  • -

#3 mrgubbala  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-September 06

Re: Bitwise XOR

Posted 14 September 2006 - 12:37 AM

for example,

int counter=0;
int reset=10;

while(1)
{
if(counter^reset)
counter++;
else
counter = counter ^ reset;
}

How can I make it even simplier, may be with a single statement?
Was This Post Helpful? 0
  • +
  • -

#4 Xing  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 19
  • View blog
  • Posts: 725
  • Joined: 22-July 06

Re: Bitwise XOR

Posted 14 September 2006 - 01:25 AM

Try this
count<10?++count:(count^=count);

Was This Post Helpful? 0
  • +
  • -

#5 born2c0de  Icon User is offline

  • printf("I'm a %XR",195936478);
  • member icon

Reputation: 180
  • View blog
  • Posts: 4,667
  • Joined: 26-November 04

Re: Bitwise XOR

Posted 14 September 2006 - 07:15 AM

That's using the ternary conditional operator very nicely.
Great stuff Xing.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1