hendian.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #ifndef H_ENDIAN_H
  2. #define H_ENDIAN_H
  3. #include "hdef.h"
  4. #define LITTLE_ENDIAN 0
  5. #define BIG_ENDIAN 1
  6. #define NET_ENDIAN BIG_ENDIAN
  7. int check_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* serialize(uint8* buf, T value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN){
  20. size_t size = sizeof(T);
  21. uint8* pDst = buf;
  22. uint8* pSrc = (uint8*)&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* deserialize(uint8* buf, T* value, int host_endian = LITTLE_ENDIAN, int buf_endian = BIG_ENDIAN){
  34. size_t size = sizeof(T);
  35. uint8* pSrc = buf;
  36. uint8* pDst = (uint8*)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 // H_ENDIAN_H