HengshanExtensions.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace HengshanPaymentTerminal
  8. {
  9. public static class HengshanExtensions
  10. {
  11. /// <summary>
  12. /// Converts a byte array, normally two bytes to an integer.
  13. /// e.g. byte array of 0x00 0x12 is converted to integer of 18.
  14. /// </summary>
  15. /// <param name="source">The source byte array</param>
  16. /// <returns>integer value</returns>
  17. public static int ToInt32(this byte[] source)
  18. {
  19. var hexTarget = new StringBuilder(source.Length * 2);
  20. foreach (byte b in source)
  21. hexTarget.AppendFormat("{0:x2}", b);
  22. return int.Parse(hexTarget.ToString(), NumberStyles.HexNumber);
  23. }
  24. /// <summary>
  25. /// Converts a char array to an unsigned short integer.
  26. /// </summary>
  27. /// <param name="source">The source char array.</param>
  28. /// <returns>An unsigned short integer value.</returns>
  29. public static ushort ToUInt16(this char[] source)
  30. {
  31. var hexTarget = new StringBuilder(source.Length * 2);
  32. foreach (byte b in source)
  33. hexTarget.AppendFormat("{0:x2}", b);
  34. return UInt16.Parse(hexTarget.ToString(), NumberStyles.HexNumber);
  35. }
  36. public static byte ToByte(this string source)
  37. {
  38. return Convert.ToByte(Int16.Parse(source, NumberStyles.HexNumber));
  39. }
  40. public static ushort ToUInt16(this string source)
  41. {
  42. return UInt16.Parse(source, NumberStyles.HexNumber);
  43. }
  44. public static uint ToUInt32(this string source)
  45. {
  46. return UInt32.Parse(source, NumberStyles.HexNumber);
  47. }
  48. }
  49. }