Boolean.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. namespace S7.Net.Types
  2. {
  3. /// <summary>
  4. /// Contains the methods to read, set and reset bits inside bytes
  5. /// </summary>
  6. public static class Boolean
  7. {
  8. /// <summary>
  9. /// Returns the value of a bit in a bit, given the address of the bit
  10. /// </summary>
  11. public static bool GetValue(byte value, int bit)
  12. {
  13. return (((int)value & (1 << bit)) != 0);
  14. }
  15. /// <summary>
  16. /// Sets the value of a bit to 1 (true), given the address of the bit. Returns
  17. /// a copy of the value with the bit set.
  18. /// </summary>
  19. /// <param name="value">The input value to modify.</param>
  20. /// <param name="bit">The index (zero based) of the bit to set.</param>
  21. /// <returns>The modified value with the bit at index set.</returns>
  22. public static byte SetBit(byte value, int bit)
  23. {
  24. SetBit(ref value, bit);
  25. return value;
  26. }
  27. /// <summary>
  28. /// Sets the value of a bit to 1 (true), given the address of the bit.
  29. /// </summary>
  30. /// <param name="value">The value to modify.</param>
  31. /// <param name="bit">The index (zero based) of the bit to set.</param>
  32. public static void SetBit(ref byte value, int bit)
  33. {
  34. value = (byte) ((value | (1 << bit)) & 0xFF);
  35. }
  36. /// <summary>
  37. /// Resets the value of a bit to 0 (false), given the address of the bit. Returns
  38. /// a copy of the value with the bit cleared.
  39. /// </summary>
  40. /// <param name="value">The input value to modify.</param>
  41. /// <param name="bit">The index (zero based) of the bit to clear.</param>
  42. /// <returns>The modified value with the bit at index cleared.</returns>
  43. public static byte ClearBit(byte value, int bit)
  44. {
  45. ClearBit(ref value, bit);
  46. return value;
  47. }
  48. /// <summary>
  49. /// Resets the value of a bit to 0 (false), given the address of the bit
  50. /// </summary>
  51. /// <param name="value">The input value to modify.</param>
  52. /// <param name="bit">The index (zero based) of the bit to clear.</param>
  53. public static void ClearBit(ref byte value, int bit)
  54. {
  55. value = (byte) (value & ~(1 << bit) & 0xFF);
  56. }
  57. }
  58. }