Advertisement
Guest User

Untitled

a guest
Nov 26th, 2015
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <stdint.h>
  5. #include <getopt.h>
  6.  
  7. #define OFFSET 2208988800ULL
  8.  
  9. int main(int argc, char *argv[]) {
  10.    
  11.     struct timeval unix;
  12.     unsigned char ntp[8];
  13.    
  14.     gettimeofday(&t, NULL);
  15.     printf("unix:\n");
  16.     printf("%ld.%06ld\n", unix->tv_sec, unix->tv_usec);
  17.    
  18.     printf("unix2ntp:\n");
  19.     unix_to_ntp(&t, ntp);
  20.     int i;
  21.     int res = 0;
  22.     for (i = 0; i < sizeof ntp; i++) {
  23.         if (i == sizeof ntp / 2)
  24.             res += printf(".");
  25.         res += printf("%02x", ntp[i]);
  26.     } /* for */
  27.     res += printf("\n");
  28.     printf("%d\n", res):
  29.    
  30.     printf("ntp2unix:\n");
  31.     ntp_to_unix(ntp, &t);
  32.     printf("%ld.%06ld\n", unix->tv_sec, unix->tv_usec);
  33.    
  34. }
  35.  
  36. void unix_to_ntp(struct timeval *unix, unsigned char *ntp[]) {
  37.    
  38.     unsigned long aux = 0;
  39.     unsigned char *p = ntp + sizeof ntp;
  40.     int i;
  41.    
  42.     aux = unix -> tv_usec;
  43.     aux <<= 32;
  44.     aux /= 1000000;
  45.    
  46.     for (i = 0; i < sizeof ntp/2; i++) {
  47.         *--p = aux & 0xFF;
  48.         aux >>= 8;
  49.     }
  50.    
  51.     aux = unix -> tv_sec;
  52.     aux += OFFSET;
  53.    
  54.     for (i; i < sizeof ntp; i++) {
  55.         *--p = aux & 0xFF;
  56.         aux >>= 8;
  57.     }
  58.    
  59. }
  60.  
  61. void ntp_to_unix(unsigned char *ntp[], struct timeval *unix) {
  62.    
  63.     unsigned long aux = 0;
  64.     unsigned char *p = ntp;
  65.     int i;
  66.    
  67.     for (i = 0; i  < sizeof ntp/2; i++) {
  68.         aux <<= 8;
  69.         aux |= *p++;
  70.     }
  71.    
  72.     aux -= OFFSET;
  73.     unix -> tv_sec = aux;
  74.    
  75.     aux = 0;
  76.     for (i; i < sizeof ntp; i++) {
  77.         aux <<= 8;
  78.         aux |= *p++;
  79.     }
  80.    
  81.     aux *= 1000000;
  82.     aux >>= 32;
  83.     unix -> tv_usec = aux;
  84.    
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement