endian.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2019 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. // Endianness abstraction layer for manipulating byte arrays within unsigned integers
  24. // ENDIAN_POS_ADDR
  25. // Bit-shift in the positive direction of addresses
  26. // Precondition: OFFSET % 8 == 0
  27. // ENDIAN_NEG_ADDR
  28. // Bit-shift in the negative direction of addresses
  29. // Precondition: OFFSET % 8 == 0
  30. // ENDIAN32_BYTE_0, A mask from the byte array {255, 0, 0, 0}
  31. // ENDIAN32_BYTE_1, A mask from the byte array {0, 255, 0, 0}
  32. // ENDIAN32_BYTE_2, A mask from the byte array {0, 0, 255, 0}
  33. // ENDIAN32_BYTE_3, A mask from the byte array {0, 0, 0, 255}
  34. // The DSR_BIG_ENDIAN flag should be given manually as a compiler argument when compiling for big-endian hardware
  35. #ifndef DFPSR_ENDIAN
  36. #define DFPSR_ENDIAN
  37. #include <stdint.h>
  38. // TODO: Detect endianness automatically
  39. #ifdef DSR_BIG_ENDIAN
  40. // TODO: Not yet tested on a big-endian machine!
  41. #define ENDIAN_POS_ADDR(VALUE,OFFSET) ((VALUE) >> (OFFSET))
  42. #define ENDIAN_NEG_ADDR(VALUE,OFFSET) ((VALUE) << (OFFSET))
  43. #define ENDIAN32_BYTE_0 0xFF000000u
  44. static_assert(false, "Big-endian mode has not been officially tested!");
  45. #else
  46. #define ENDIAN_POS_ADDR(VALUE,OFFSET) ((VALUE) << (OFFSET))
  47. #define ENDIAN_NEG_ADDR(VALUE,OFFSET) ((VALUE) >> (OFFSET))
  48. #define ENDIAN32_BYTE_0 0x000000FFu
  49. #endif
  50. #define ENDIAN32_BYTE_1 ENDIAN_POS_ADDR(ENDIAN32_BYTE_0, 8)
  51. #define ENDIAN32_BYTE_2 ENDIAN_POS_ADDR(ENDIAN32_BYTE_0, 16)
  52. #define ENDIAN32_BYTE_3 ENDIAN_POS_ADDR(ENDIAN32_BYTE_0, 24)
  53. #endif