ntoh.c 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. /*
  6. * A test program for PR_htons, PR_ntohs, PR_htonl, PR_ntohl,
  7. * PR_htonll, and PR_ntohll.
  8. */
  9. #include "prnetdb.h"
  10. #include <stdio.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. /* Byte sequence in network byte order */
  14. static unsigned char bytes_n[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  15. /* Integers in host byte order */
  16. static PRUint16 s_h = 0x0102;
  17. static PRUint32 l_h = 0x01020304;
  18. static PRUint64 ll_h = LL_INIT(0x01020304, 0x05060708);
  19. int main(int argc, char **argv)
  20. {
  21. union {
  22. PRUint16 s;
  23. PRUint32 l;
  24. PRUint64 ll;
  25. unsigned char bytes[8];
  26. } un;
  27. un.s = s_h;
  28. printf("%u %u\n",
  29. un.bytes[0], un.bytes[1]);
  30. un.s = PR_htons(un.s);
  31. printf("%u %u\n",
  32. un.bytes[0], un.bytes[1]);
  33. if (memcmp(un.bytes, bytes_n, 2)) {
  34. fprintf(stderr, "PR_htons failed\n");
  35. exit(1);
  36. }
  37. un.s = PR_ntohs(un.s);
  38. printf("%u %u\n",
  39. un.bytes[0], un.bytes[1]);
  40. if (un.s != s_h) {
  41. fprintf(stderr, "PR_ntohs failed\n");
  42. exit(1);
  43. }
  44. un.l = l_h;
  45. printf("%u %u %u %u\n",
  46. un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]);
  47. un.l = PR_htonl(un.l);
  48. printf("%u %u %u %u\n",
  49. un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]);
  50. if (memcmp(un.bytes, bytes_n, 4)) {
  51. fprintf(stderr, "PR_htonl failed\n");
  52. exit(1);
  53. }
  54. un.l = PR_ntohl(un.l);
  55. printf("%u %u %u %u\n",
  56. un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]);
  57. if (un.l != l_h) {
  58. fprintf(stderr, "PR_ntohl failed\n");
  59. exit(1);
  60. }
  61. un.ll = ll_h;
  62. printf("%u %u %u %u %u %u %u %u\n",
  63. un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3],
  64. un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]);
  65. un.ll = PR_htonll(un.ll);
  66. printf("%u %u %u %u %u %u %u %u\n",
  67. un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3],
  68. un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]);
  69. if (memcmp(un.bytes, bytes_n, 8)) {
  70. fprintf(stderr, "PR_htonll failed\n");
  71. exit(1);
  72. }
  73. un.ll = PR_ntohll(un.ll);
  74. printf("%u %u %u %u %u %u %u %u\n",
  75. un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3],
  76. un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]);
  77. if (LL_NE(un.ll, ll_h)) {
  78. fprintf(stderr, "PR_ntohll failed\n");
  79. exit(1);
  80. }
  81. printf("PASS\n");
  82. return 0;
  83. }