Posted By

rengber on 03/27/07


Tagged

operator bitwise


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

umang_nine


Bitwise operations on Integers


 / Published in: C#
 

  1. //Bitwise Operations
  2.  
  3. //Turn a bit on
  4. int startVal = 4; //100
  5. int bitVal = 2; //010
  6. int newVal = startVal | bitVal; //110 (6)
  7. //Alternatively
  8. startVal |= bitVal;
  9.  
  10. //Turn a bit off
  11. int startVal = 7; //111
  12. int bitVal = 5; //101
  13. int newVal = startVal & bitVal; //101 (5)
  14. //Alternatively
  15. startVal &= bitVal;
  16.  
  17.  
  18. //Query bit status
  19. int startVal = 6; //110
  20. int bitVal = 4; //100
  21. int newVal = startVal & bitVal; //100
  22. if(newVal != 0)
  23. {
  24. //Bit was on.
  25. }
  26.  
  27. int startVal = 6; //110
  28. int bitVal = 1; //001
  29. int newVal = startVal & bitVal; //000
  30. if(newVal == 0)
  31. {
  32. //Bit was off.
  33. }

Report this snippet  

You need to login to post a comment.