endianness.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //
  2. // Created by Avilov Vasily on 10.06.2023.
  3. //
  4. #ifndef FLIPPERZERO_FIRMWARE_ENDIANNESS_H
  5. #define FLIPPERZERO_FIRMWARE_ENDIANNESS_H
  6. #include <machine/endian.h>
  7. inline static void store16(uint8_t* b, uint16_t i) {
  8. memcpy(b, &i, 2);
  9. }
  10. inline static void store32(uint8_t* b, uint32_t i) {
  11. memcpy(b, &i, 4);
  12. }
  13. inline static uint16_t load16(uint8_t* b) {
  14. uint16_t x;
  15. memcpy(&x, b, 2);
  16. return x;
  17. }
  18. inline static uint32_t load32(uint8_t* b) {
  19. uint32_t x;
  20. memcpy(&x, b, 4);
  21. return x;
  22. }
  23. #if BYTE_ORDER == BIG_ENDIAN
  24. #define htobe16(x) (x)
  25. #define htobe32(x) (x)
  26. #define htole16(x) __builtin_bswap16(x)
  27. #define htole32(x) __builtin_bswap32(x)
  28. #define be16toh(x) (x)
  29. #define be32toh(x) (x)
  30. #define le16toh(x) __builtin_bswap16(x)
  31. #define le32toh(x) __builtin_bswap32(x)
  32. #elif BYTE_ORDER == LITTLE_ENDIAN
  33. #define htobe16(x) __builtin_bswap16(x)
  34. #define htobe32(x) __builtin_bswap32(x)
  35. #define htole16(x) (x)
  36. #define htole32(x) (x)
  37. #define be16toh(x) __builtin_bswap16(x)
  38. #define be32toh(x) __builtin_bswap32(x)
  39. #define le16toh(x) (x)
  40. #define le32toh(x) (x)
  41. #else
  42. #error "What kind of system is this?"
  43. #endif
  44. #define load16_le(b) (le16toh(load16(b)))
  45. #define load32_le(b) (le32toh(load32(b)))
  46. #define store16_le(b, i) (store16(b, htole16(i)))
  47. #define store32_le(b, i) (store32(b, htole32(i)))
  48. #define load16_be(b) (be16toh(load16(b)))
  49. #define load32_be(b) (be32toh(load32(b)))
  50. #define store16_be(b, i) (store16(b, htobe16(i)))
  51. #define store32_be(b, i) (store32(b, htobe32(i)))
  52. #endif //FLIPPERZERO_FIRMWARE_ENDIANNESS_H