ntoh.c (2466B)
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 /* 7 * A test program for PR_htons, PR_ntohs, PR_htonl, PR_ntohl, 8 * PR_htonll, and PR_ntohll. 9 */ 10 11 #include "prnetdb.h" 12 13 #include <stdio.h> 14 #include <string.h> 15 #include <stdlib.h> 16 17 /* Byte sequence in network byte order */ 18 static unsigned char bytes_n[8] = {1, 2, 3, 4, 5, 6, 7, 8}; 19 20 /* Integers in host byte order */ 21 static PRUint16 s_h = 0x0102; 22 static PRUint32 l_h = 0x01020304; 23 static PRUint64 ll_h = LL_INIT(0x01020304, 0x05060708); 24 25 int main(int argc, char** argv) { 26 union { 27 PRUint16 s; 28 PRUint32 l; 29 PRUint64 ll; 30 unsigned char bytes[8]; 31 } un; 32 33 un.s = s_h; 34 printf("%u %u\n", un.bytes[0], un.bytes[1]); 35 un.s = PR_htons(un.s); 36 printf("%u %u\n", un.bytes[0], un.bytes[1]); 37 if (memcmp(un.bytes, bytes_n, 2)) { 38 fprintf(stderr, "PR_htons failed\n"); 39 exit(1); 40 } 41 un.s = PR_ntohs(un.s); 42 printf("%u %u\n", un.bytes[0], un.bytes[1]); 43 if (un.s != s_h) { 44 fprintf(stderr, "PR_ntohs failed\n"); 45 exit(1); 46 } 47 48 un.l = l_h; 49 printf("%u %u %u %u\n", un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); 50 un.l = PR_htonl(un.l); 51 printf("%u %u %u %u\n", un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); 52 if (memcmp(un.bytes, bytes_n, 4)) { 53 fprintf(stderr, "PR_htonl failed\n"); 54 exit(1); 55 } 56 un.l = PR_ntohl(un.l); 57 printf("%u %u %u %u\n", un.bytes[0], un.bytes[1], un.bytes[2], un.bytes[3]); 58 if (un.l != l_h) { 59 fprintf(stderr, "PR_ntohl failed\n"); 60 exit(1); 61 } 62 63 un.ll = ll_h; 64 printf("%u %u %u %u %u %u %u %u\n", un.bytes[0], un.bytes[1], un.bytes[2], 65 un.bytes[3], un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); 66 un.ll = PR_htonll(un.ll); 67 printf("%u %u %u %u %u %u %u %u\n", un.bytes[0], un.bytes[1], un.bytes[2], 68 un.bytes[3], 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", un.bytes[0], un.bytes[1], un.bytes[2], 75 un.bytes[3], un.bytes[4], un.bytes[5], un.bytes[6], un.bytes[7]); 76 if (LL_NE(un.ll, ll_h)) { 77 fprintf(stderr, "PR_ntohll failed\n"); 78 exit(1); 79 } 80 81 printf("PASS\n"); 82 return 0; 83 }