Helper.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MSHO.Collection.Service
  7. {
  8. public static class Helper {
  9. public static byte[] Int32ToBytes(this int n) {
  10. var bytes = new byte[4];
  11. bytes[0] = (byte)(n & 0xFF);
  12. bytes[1] = (byte)(n >> 8 & 0xFF);
  13. bytes[2] = (byte)(n >> 16 & 0xFF);
  14. bytes[3] = (byte)(n >> 24 & 0xFF);
  15. return bytes;
  16. }
  17. public static int BytesToInt32(this byte[] bytes, int index = 0) {
  18. int n = 0;
  19. if (bytes != null && bytes.Length >= 4) {
  20. n = bytes[index + 3];
  21. n = n << 8 | bytes[index + 2];
  22. n = n << 8 | bytes[index + 1];
  23. n = n << 8 | bytes[index + 0];
  24. }
  25. return n;
  26. }
  27. public static byte[] LongToBytes(this long n)
  28. {
  29. var bytes = new byte[sizeof(long)];
  30. for (var i = 0; i < sizeof(long); i++) {
  31. bytes[i] = (byte)((n >> (i*8)) & 0xFF);
  32. }
  33. return bytes;
  34. }
  35. public static long BytesToLong(this byte[] bytes, int index = 0)
  36. {
  37. long n = 0;
  38. if (bytes != null && bytes.Length >= sizeof(long))
  39. {
  40. for (var i = sizeof(long) - 1; i >=0; i--) {
  41. n = n << 8 | bytes[index + i];
  42. }
  43. }
  44. return n;
  45. }
  46. public static T GetEnum<T>(string val, T d) where T : struct
  47. {
  48. T result = default(T);
  49. if (!Enum.TryParse<T>(val, out result))
  50. {
  51. result = d;
  52. }
  53. return result;
  54. }
  55. }
  56. }