North American Network Operators Group

Date Prev | Date Next | Date Index | Thread Index | Author Index | Historical

Re: interger to I P address

  • From: David Champion
  • Date: Wed Aug 27 14:27:12 2008

> 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.    [email protected]    NSIT    University of Chicago