StringHelper.cs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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(String.Format(CultureInfo.InvariantCulture,
  24. "The binary key cannot have an odd number of digits: {0}", hexString));
  25. }
  26. var hexAsBytes = new byte[hexString.Length / 2];
  27. for (int index = 0; index < hexAsBytes.Length; index++)
  28. {
  29. string byteValue = "";
  30. byteValue += hexString[index * 2];
  31. byteValue += hexString[index * 2 + 1];
  32. hexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
  33. }
  34. return hexAsBytes;
  35. }
  36. }
  37. }