StringHelper.cs 1009 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Text;
  5. namespace Common.Helper
  6. {
  7. public static class StringHelper
  8. {
  9. public static IEnumerable<byte> ToBytes(this string str)
  10. {
  11. byte[] byteArray = Encoding.Default.GetBytes(str);
  12. return byteArray;
  13. }
  14. public static byte[] ToByteArray(this string str)
  15. {
  16. byte[] byteArray = Encoding.Default.GetBytes(str);
  17. return byteArray;
  18. }
  19. public static byte[] HexToBytes(this string hexString)
  20. {
  21. if (hexString.Length % 2 != 0)
  22. {
  23. throw new ArgumentException($"The binary key cannot have an odd number of digits: {hexString}");
  24. }
  25. var hexAsBytes = new byte[hexString.Length / 2];
  26. for (int index = 0; index < hexAsBytes.Length; index++)
  27. {
  28. string byteValue = "";
  29. byteValue += hexString[index * 2];
  30. byteValue += hexString[index * 2 + 1];
  31. hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  32. }
  33. return hexAsBytes;
  34. }
  35. }
  36. }