endianness.h 1.5 KB

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