endian.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the License); you may
  5. * not use this file except in compliance with the License.
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. */
  9. #ifndef GMSSL_ENDIAN_H
  10. #define GMSSL_ENDIAN_H
  11. /* Big Endian R/W */
  12. #define GETU16(p) \
  13. ((uint16_t)(p)[0] << 8 | \
  14. (uint16_t)(p)[1])
  15. #define GETU32(p) \
  16. ((uint32_t)(p)[0] << 24 | \
  17. (uint32_t)(p)[1] << 16 | \
  18. (uint32_t)(p)[2] << 8 | \
  19. (uint32_t)(p)[3])
  20. #define GETU64(p) \
  21. ((uint64_t)(p)[0] << 56 | \
  22. (uint64_t)(p)[1] << 48 | \
  23. (uint64_t)(p)[2] << 40 | \
  24. (uint64_t)(p)[3] << 32 | \
  25. (uint64_t)(p)[4] << 24 | \
  26. (uint64_t)(p)[5] << 16 | \
  27. (uint64_t)(p)[6] << 8 | \
  28. (uint64_t)(p)[7])
  29. // 注意:PUTU32(buf, val++) 会出错!
  30. #define PUTU16(p,V) \
  31. ((p)[0] = (uint8_t)((V) >> 8), \
  32. (p)[1] = (uint8_t)(V))
  33. #define PUTU32(p,V) \
  34. ((p)[0] = (uint8_t)((V) >> 24), \
  35. (p)[1] = (uint8_t)((V) >> 16), \
  36. (p)[2] = (uint8_t)((V) >> 8), \
  37. (p)[3] = (uint8_t)(V))
  38. #define PUTU64(p,V) \
  39. ((p)[0] = (uint8_t)((V) >> 56), \
  40. (p)[1] = (uint8_t)((V) >> 48), \
  41. (p)[2] = (uint8_t)((V) >> 40), \
  42. (p)[3] = (uint8_t)((V) >> 32), \
  43. (p)[4] = (uint8_t)((V) >> 24), \
  44. (p)[5] = (uint8_t)((V) >> 16), \
  45. (p)[6] = (uint8_t)((V) >> 8), \
  46. (p)[7] = (uint8_t)(V))
  47. /* Little Endian R/W */
  48. #define GETU16_LE(p) (*(const uint16_t *)(p))
  49. #define GETU32_LE(p) (*(const uint32_t *)(p))
  50. #define GETU64_LE(p) (*(const uint64_t *)(p))
  51. #define PUTU16_LE(p,V) *(uint16_t *)(p) = (V)
  52. #define PUTU32_LE(p,V) *(uint32_t *)(p) = (V)
  53. #define PUTU64_LE(p,V) *(uint64_t *)(p) = (V)
  54. /* Rotate */
  55. #define ROL32(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
  56. #define ROL64(a,n) (((a)<<(n))|((a)>>(64-(n))))
  57. #define ROR32(a,n) ROL32((a),32-(n))
  58. #define ROR64(a,n) ROL64(a,64-n)
  59. #endif