common_endian.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. This file is part of GNUnet.
  3. Copyright (C) 2001, 2002, 2003, 2004, 2006, 2012 GNUnet e.V.
  4. GNUnet is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Affero General Public License as published
  6. by the Free Software Foundation, either version 3 of the License,
  7. or (at your option) any later version.
  8. GNUnet is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Affero General Public License for more details.
  12. You should have received a copy of the GNU Affero General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. SPDX-License-Identifier: AGPL3.0-or-later
  15. */
  16. /**
  17. * @file util/common_endian.c
  18. * @brief endian conversion helpers
  19. * @author Christian Grothoff
  20. * @author Gabor X Toth
  21. */
  22. #include "platform.h"
  23. #include "gnunet_crypto_lib.h"
  24. #define LOG(kind, ...) GNUNET_log_from (kind, "util-common-endian", __VA_ARGS__)
  25. #ifndef htonbe64
  26. uint64_t
  27. GNUNET_htonll (uint64_t n)
  28. {
  29. #if __BYTE_ORDER == __BIG_ENDIAN
  30. return n;
  31. #elif __BYTE_ORDER == __LITTLE_ENDIAN
  32. return (((uint64_t) htonl (n)) << 32) + htonl (n >> 32);
  33. #else
  34. #error byteorder undefined
  35. #endif
  36. }
  37. #endif
  38. #ifndef be64toh
  39. uint64_t
  40. GNUNET_ntohll (uint64_t n)
  41. {
  42. #if __BYTE_ORDER == __BIG_ENDIAN
  43. return n;
  44. #elif __BYTE_ORDER == __LITTLE_ENDIAN
  45. return (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32);
  46. #else
  47. #error byteorder undefined
  48. #endif
  49. }
  50. #endif
  51. /**
  52. * Convert double to network-byte-order.
  53. * @param d the value in network byte order
  54. * @return the same value in host byte order
  55. */
  56. double
  57. GNUNET_hton_double (double d)
  58. {
  59. double res;
  60. uint64_t *in = (uint64_t *) &d;
  61. uint64_t *out = (uint64_t *) &res;
  62. out[0] = GNUNET_htonll (in[0]);
  63. return res;
  64. }
  65. /**
  66. * Convert double to host-byte-order
  67. * @param d the value in network byte order
  68. * @return the same value in host byte order
  69. */
  70. double
  71. GNUNET_ntoh_double (double d)
  72. {
  73. double res;
  74. uint64_t *in = (uint64_t *) &d;
  75. uint64_t *out = (uint64_t *) &res;
  76. out[0] = GNUNET_ntohll (in[0]);
  77. return res;
  78. }
  79. /* end of common_endian.c */