Bitwise operations on Integers


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.