HengshanExtensions.cs 1.7 KB

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