ByteHelper.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using System;
  2. using System.Text;
  3. namespace ETModel
  4. {
  5. public static class ByteHelper
  6. {
  7. public static string ToHex(this byte b)
  8. {
  9. return b.ToString("X2");
  10. }
  11. public static string ToHex(this byte[] bytes)
  12. {
  13. StringBuilder stringBuilder = new StringBuilder();
  14. foreach (byte b in bytes)
  15. {
  16. stringBuilder.Append(b.ToString("X2"));
  17. }
  18. return stringBuilder.ToString();
  19. }
  20. public static string ToHex(this byte[] bytes, string format)
  21. {
  22. StringBuilder stringBuilder = new StringBuilder();
  23. foreach (byte b in bytes)
  24. {
  25. stringBuilder.Append(b.ToString(format));
  26. }
  27. return stringBuilder.ToString();
  28. }
  29. public static string ToHex(this byte[] bytes, int offset, int count)
  30. {
  31. StringBuilder stringBuilder = new StringBuilder();
  32. for (int i = offset; i < offset + count; ++i)
  33. {
  34. stringBuilder.Append(bytes[i].ToString("X2"));
  35. }
  36. return stringBuilder.ToString();
  37. }
  38. public static string ToStr(this byte[] bytes)
  39. {
  40. return Encoding.Default.GetString(bytes);
  41. }
  42. public static string ToStr(this byte[] bytes, int index, int count)
  43. {
  44. return Encoding.Default.GetString(bytes, index, count);
  45. }
  46. public static string Utf8ToStr(this byte[] bytes)
  47. {
  48. return Encoding.UTF8.GetString(bytes);
  49. }
  50. public static string Utf8ToStr(this byte[] bytes, int index, int count)
  51. {
  52. return Encoding.UTF8.GetString(bytes, index, count);
  53. }
  54. public static void WriteTo(this byte[] bytes, int offset, uint num)
  55. {
  56. bytes[offset] = (byte)(num & 0xff);
  57. bytes[offset + 1] = (byte)((num & 0xff00) >> 8);
  58. bytes[offset + 2] = (byte)((num & 0xff0000) >> 16);
  59. bytes[offset + 3] = (byte)((num & 0xff000000) >> 24);
  60. }
  61. public static void WriteTo(this byte[] bytes, int offset, int num)
  62. {
  63. bytes[offset] = (byte)(num & 0xff);
  64. bytes[offset + 1] = (byte)((num & 0xff00) >> 8);
  65. bytes[offset + 2] = (byte)((num & 0xff0000) >> 16);
  66. bytes[offset + 3] = (byte)((num & 0xff000000) >> 24);
  67. }
  68. public static void WriteTo(this byte[] bytes, int offset, short num)
  69. {
  70. bytes[offset] = (byte)(num & 0xff);
  71. bytes[offset + 1] = (byte)((num & 0xff00) >> 8);
  72. }
  73. public static void WriteTo(this byte[] bytes, int offset, ushort num)
  74. {
  75. bytes[offset] = (byte)(num & 0xff);
  76. bytes[offset + 1] = (byte)((num & 0xff00) >> 8);
  77. }
  78. }
  79. }