ByteHelper.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Text;
  3. namespace Model
  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. }
  55. }