ByteHelper.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Text;
  3. namespace Base
  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 Utf8ToStr(this byte[] bytes)
  43. {
  44. return Encoding.UTF8.GetString(bytes);
  45. }
  46. public static byte[] Reverse(this byte[] bytes)
  47. {
  48. Array.Reverse(bytes);
  49. return bytes;
  50. }
  51. }
  52. }