We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Posted By

rengber on 03/27/07


Tagged

operator bitwise


Versions (?)


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.