ByteHelper.cs 2.9 KB

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