binary.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (C) 2023 Kovid Goyal <kovid at kovidgoyal.net>
  3. *
  4. * Distributed under terms of the GPL3 license.
  5. */
  6. #pragma once
  7. #include <stdint.h>
  8. static inline uint16_t
  9. be16dec(const void *pp) {
  10. uint8_t const *p = (uint8_t const *)pp;
  11. return (((unsigned)p[0] << 8) | p[1]);
  12. }
  13. static inline uint32_t
  14. be32dec(const void *pp) {
  15. uint8_t const *p = (uint8_t const *)pp;
  16. return (((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) |
  17. ((uint32_t)p[2] << 8) | p[3]);
  18. }
  19. static inline uint64_t
  20. be64dec(const void *pp) {
  21. uint8_t const *p = (uint8_t const *)pp;
  22. return (((uint64_t)be32dec(p) << 32) | be32dec(p + 4));
  23. }
  24. static inline uint16_t
  25. le16dec(const void *pp) {
  26. uint8_t const *p = (uint8_t const *)pp;
  27. return (((unsigned)p[1] << 8) | p[0]);
  28. }
  29. static inline uint32_t
  30. le32dec(const void *pp) {
  31. uint8_t const *p = (uint8_t const *)pp;
  32. return (((uint32_t)p[3] << 24) | ((uint32_t)p[2] << 16) |
  33. ((uint32_t)p[1] << 8) | p[0]);
  34. }
  35. static inline uint64_t
  36. le64dec(const void *pp) {
  37. uint8_t const *p = (uint8_t const *)pp;
  38. return (((uint64_t)le32dec(p + 4) << 32) | le32dec(p));
  39. }
  40. static inline void
  41. be16enc(void *pp, uint16_t u) {
  42. uint8_t *p = (uint8_t *)pp;
  43. p[0] = (u >> 8) & 0xff;
  44. p[1] = u & 0xff;
  45. }
  46. static inline void
  47. be32enc(void *pp, uint32_t u) {
  48. uint8_t *p = (uint8_t *)pp;
  49. p[0] = (u >> 24) & 0xff;
  50. p[1] = (u >> 16) & 0xff;
  51. p[2] = (u >> 8) & 0xff;
  52. p[3] = u & 0xff;
  53. }
  54. static inline void
  55. be64enc(void *pp, uint64_t u) {
  56. uint8_t *p = (uint8_t *)pp;
  57. be32enc(p, (uint32_t)(u >> 32));
  58. be32enc(p + 4, (uint32_t)(u & 0xffffffffU));
  59. }
  60. static inline void
  61. le16enc(void *pp, uint16_t u) {
  62. uint8_t *p = (uint8_t *)pp;
  63. p[0] = u & 0xff;
  64. p[1] = (u >> 8) & 0xff;
  65. }
  66. static inline void
  67. le32enc(void *pp, uint32_t u) {
  68. uint8_t *p = (uint8_t *)pp;
  69. p[0] = u & 0xff;
  70. p[1] = (u >> 8) & 0xff;
  71. p[2] = (u >> 16) & 0xff;
  72. p[3] = (u >> 24) & 0xff;
  73. }
  74. static inline void
  75. le64enc(void *pp, uint64_t u) {
  76. uint8_t *p = (uint8_t *)pp;
  77. le32enc(p, (uint32_t)(u & 0xffffffffU));
  78. le32enc(p + 4, (uint32_t)(u >> 32));
  79. }