hendian.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #ifndef HW_ENDIAN_H_
  2. #define HW_ENDIAN_H_
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include "hplatform.h"
  6. #include "hdef.h"
  7. int detect_endian() {
  8. union {
  9. char c;
  10. short s;
  11. } u;
  12. u.s = 0x1122;
  13. if (u.c == 0x11) {
  14. return BIG_ENDIAN;
  15. }
  16. return LITTLE_ENDIAN;
  17. }
  18. template <typename T>
  19. uint8_t* serialize(uint8_t* buf, T value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) {
  20. size_t size = sizeof(T);
  21. uint8_t* pDst = buf;
  22. uint8_t* pSrc = (uint8_t*)&value;
  23. if (host_endian == buf_endian) {
  24. memcpy(pDst, pSrc, size);
  25. } else {
  26. for (int i = 0; i < size; ++i) {
  27. pDst[i] = pSrc[size-i-1];
  28. }
  29. }
  30. return buf+size;
  31. }
  32. template <typename T>
  33. uint8_t* deserialize(uint8_t* buf, T* value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN) {
  34. size_t size = sizeof(T);
  35. uint8_t* pSrc = buf;
  36. uint8_t* pDst = (uint8_t*)value;
  37. if (host_endian == buf_endian) {
  38. memcpy(pDst, pSrc, size);
  39. } else {
  40. for (int i = 0; i < size; ++i) {
  41. pDst[i] = pSrc[size-i-1];
  42. }
  43. }
  44. return buf+size;
  45. }
  46. #endif // HW_ENDIAN_H_