nanog mailing list archives

Re: interger to I P address


From: David Champion <dgc () uchicago edu>
Date: Wed, 27 Aug 2008 13:27:06 -0500

Actually, who needs loops for that?
...
(unsigned char)(((char*)&i)[3]),
(unsigned char)(((char*)&i)[2]),
(unsigned char)(((char*)&i)[1]),
(unsigned char)(((char*)&i)[0])

Let data structures work for you.

#include <stdio.h>

main(int argc, char *argv[])
{
        union {
                unsigned int i;
                unsigned char c[4];
        } ip;
        int i = 0;

        ip.i = 1089055123;
        /* endian-neutral iteration: */
        printf("%d.%d.%d.%d\n", ip.c[i++], ip.c[i++], ip.c[i++], ip.c[i++]);
        return 0;
}


$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
obase=256
1089055123
 064 233 169 147

Curse you with your large number bases.  But if you don't do GNU:

dc <<EOF
[0 sd
 [d 10 % 48 + Sm ld 1 + sd 10 / d 0 <M] sM lMx
 [LmP ld 1 - d sd 0 <M] sM lMx
] sN
1089055123
[[.]P] sP
4so [d 256 % Si 256 / lo 1 - dso 0 <O] sO lOx
4so [Li lNx lo 1 - dd so 0 <P 0 <O] sO lOx
[
]P
EOF

-- 
 -D.    dgc () uchicago edu    NSIT    University of Chicago


Current thread: