Endian 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
  2. *
  3. * This library is open source and may be redistributed and/or modified under
  4. * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
  5. * (at your option) any later version. The full license is in LICENSE file
  6. * included with this distribution, and on the openscenegraph.org website.
  7. *
  8. * This library is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * OpenSceneGraph Public License for more details.
  12. */
  13. #ifndef OSG_ENDIAN
  14. #define OSG_ENDIAN 1
  15. #include <algorithm>
  16. namespace osg {
  17. enum Endian
  18. {
  19. BigEndian,
  20. LittleEndian
  21. };
  22. inline Endian getCpuByteOrder()
  23. {
  24. union {
  25. char big_endian_1[2];
  26. short is_it_really_1;
  27. } u;
  28. u.big_endian_1[0] = 0;
  29. u.big_endian_1[1] = 1;
  30. if (u.is_it_really_1 == 1)
  31. return BigEndian;
  32. else
  33. return LittleEndian;
  34. }
  35. inline void swapBytes( char* in, unsigned int size )
  36. {
  37. char* start = in;
  38. char* end = start+size-1;
  39. while (start<end)
  40. {
  41. std::swap(*start++,*end--);
  42. }
  43. }
  44. inline void swapBytes2( char* in )
  45. {
  46. std::swap(in[0],in[1]);
  47. }
  48. inline void swapBytes4( char* in )
  49. {
  50. std::swap(in[0],in[3]);
  51. std::swap(in[1],in[2]);
  52. }
  53. inline void swapBytes8( char* in )
  54. {
  55. std::swap(in[0],in[7]);
  56. std::swap(in[1],in[6]);
  57. std::swap(in[2],in[5]);
  58. std::swap(in[3],in[4]);
  59. }
  60. inline void swapBytes16( char* in )
  61. {
  62. std::swap(in[0],in[15]);
  63. std::swap(in[1],in[14]);
  64. std::swap(in[2],in[13]);
  65. std::swap(in[3],in[12]);
  66. std::swap(in[4],in[11]);
  67. std::swap(in[5],in[10]);
  68. std::swap(in[6],in[9]);
  69. std::swap(in[7],in[8]);
  70. }
  71. template<typename T>
  72. void swapBytes(T& t) { swapBytes(reinterpret_cast<char*>(&t), sizeof(T)); }
  73. }
  74. #endif