endian.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2010-2016 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
  4. */
  5. #ifndef BX_ENDIAN_H_HEADER_GUARD
  6. #define BX_ENDIAN_H_HEADER_GUARD
  7. #include "bx.h"
  8. namespace bx
  9. {
  10. inline uint16_t endianSwap(uint16_t _in)
  11. {
  12. return (_in>>8) | (_in<<8);
  13. }
  14. inline uint32_t endianSwap(uint32_t _in)
  15. {
  16. return (_in>>24) | (_in<<24)
  17. | ( (_in&0x00ff0000)>>8) | ( (_in&0x0000ff00)<<8)
  18. ;
  19. }
  20. inline uint64_t endianSwap(uint64_t _in)
  21. {
  22. return (_in>>56) | (_in<<56)
  23. | ( (_in&UINT64_C(0x00ff000000000000) )>>40) | ( (_in&UINT64_C(0x000000000000ff00) )<<40)
  24. | ( (_in&UINT64_C(0x0000ff0000000000) )>>24) | ( (_in&UINT64_C(0x0000000000ff0000) )<<24)
  25. | ( (_in&UINT64_C(0x000000ff00000000) )>>8) | ( (_in&UINT64_C(0x00000000ff000000) )<<8)
  26. ;
  27. }
  28. inline int16_t endianSwap(int16_t _in)
  29. {
  30. return (int16_t)endianSwap( (uint16_t)_in);
  31. }
  32. inline int32_t endianSwap(int32_t _in)
  33. {
  34. return (int32_t)endianSwap( (uint32_t)_in);
  35. }
  36. inline int64_t endianSwap(int64_t _in)
  37. {
  38. return (int64_t)endianSwap( (uint64_t)_in);
  39. }
  40. /// Input argument is encoded as little endian, convert it if neccessary
  41. /// depending on host CPU endianess.
  42. template <typename Ty>
  43. inline Ty toLittleEndian(const Ty _in)
  44. {
  45. #if BX_CPU_ENDIAN_BIG
  46. return endianSwap(_in);
  47. #else
  48. return _in;
  49. #endif // BX_CPU_ENDIAN_BIG
  50. }
  51. /// Input argument is encoded as big endian, convert it if neccessary
  52. /// depending on host CPU endianess.
  53. template <typename Ty>
  54. inline Ty toBigEndian(const Ty _in)
  55. {
  56. #if BX_CPU_ENDIAN_LITTLE
  57. return endianSwap(_in);
  58. #else
  59. return _in;
  60. #endif // BX_CPU_ENDIAN_LITTLE
  61. }
  62. /// If _littleEndian is true, converts input argument to from little endian
  63. /// to host CPU endiness.
  64. template <typename Ty>
  65. inline Ty toHostEndian(const Ty _in, bool _fromLittleEndian)
  66. {
  67. #if BX_CPU_ENDIAN_LITTLE
  68. return _fromLittleEndian ? _in : endianSwap(_in);
  69. #else
  70. return _fromLittleEndian ? endianSwap(_in) : _in;
  71. #endif // BX_CPU_ENDIAN_LITTLE
  72. }
  73. } // namespace bx
  74. #endif // BX_ENDIAN_H_HEADER_GUARD