You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.2 KiB

  1. #if !NET20
  2. using System;
  3. namespace Apewer.WebSocket
  4. {
  5. internal static class IntExtensions
  6. {
  7. public static byte[] ToBigEndianBytes<T>(this int source)
  8. {
  9. byte[] bytes;
  10. var type = typeof(T);
  11. if (type == typeof(ushort))
  12. bytes = BitConverter.GetBytes((ushort)source);
  13. else if (type == typeof(ulong))
  14. bytes = BitConverter.GetBytes((ulong)source);
  15. else if (type == typeof(int))
  16. bytes = BitConverter.GetBytes(source);
  17. else
  18. throw new InvalidCastException("Cannot be cast to T");
  19. if (BitConverter.IsLittleEndian)
  20. Array.Reverse(bytes);
  21. return bytes;
  22. }
  23. public static int ToLittleEndianInt(this byte[] source)
  24. {
  25. if(BitConverter.IsLittleEndian)
  26. Array.Reverse(source);
  27. if(source.Length == 2)
  28. return BitConverter.ToUInt16(source, 0);
  29. if(source.Length == 8)
  30. return (int)BitConverter.ToUInt64(source, 0);
  31. throw new ArgumentException("Unsupported Size");
  32. }
  33. }
  34. }
  35. #endif