BitUtils.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. namespace STUN.Utils
  6. {
  7. public static class BitUtils
  8. {
  9. public static IEnumerable<byte> ToBe(this int num)
  10. {
  11. var res = BitConverter.GetBytes(num);
  12. return BitConverter.IsLittleEndian ? res.Reverse() : res;
  13. }
  14. public static IEnumerable<byte> ToBe(this ushort num)
  15. {
  16. var res = BitConverter.GetBytes(num);
  17. return BitConverter.IsLittleEndian ? res.Reverse() : res;
  18. }
  19. public static ushort FromBe(byte b1, byte b2)
  20. {
  21. return BitConverter.ToUInt16(BitConverter.IsLittleEndian ? new[] { b2, b1 } : new[] { b1, b2 }, 0);
  22. }
  23. public static ushort FromBe(IEnumerable<byte> b)
  24. {
  25. return BitConverter.ToUInt16(BitConverter.IsLittleEndian ? b.Reverse().ToArray() : b.ToArray(), 0);
  26. }
  27. public static int FromBeToInt(IEnumerable<byte> b)
  28. {
  29. return BitConverter.ToInt32(BitConverter.IsLittleEndian ? b.Reverse().ToArray() : b.ToArray(), 0);
  30. }
  31. public static IEnumerable<byte> GetRandomBytes(int n)
  32. {
  33. var temp = new byte[n];
  34. using var rng = new RNGCryptoServiceProvider();
  35. rng.GetBytes(temp);
  36. return temp;
  37. }
  38. public static bool IsEqual(this IEnumerable<byte>? a, IEnumerable<byte>? b)
  39. {
  40. return a != null && b != null && a.SequenceEqual(b);
  41. }
  42. }
  43. }