On Fri, 2006-03-31 at 21:00 -0500, Jason Stephenson wrote:
> Stephen Ryan wrote:
> > hostmask = (1 << (32 - n)) - 1
> > netmask = ~ hostmask
> 
> Doh! That's so obvious, so obviously, I overlooked it. ;)

Well, yes, of course :-)

> > 
> > 1 << (32 - n) in binary is (n-1) '0' bits, a '1', then (32 - n) '0'
> > bits.  Subtracting 1 from that gives n '0' bits followed by (32 - n) '1'
> > bits.  The 'not' operator flips all the bits for the netmask.
> > 
> > This works for /1 through /32 networks, even though some of those are
> > nonsensical.  A /0 might break this because of overflow (1 << (32 -n)
> > overflows a 32-bit integer); theoretically, it should work even for /0
> > so long as 1 << (32-n) returns 0 (32-bit gcc 4.0 on my Athlon64 desktop
> > computes this correctly, but complains 'warning: left shift count >=
> > width of type' while compiling.  Anyway, if you're running a /0, you've
> > got other, bigger problems.
> 
> Using gcc 3.4.4 on a 32-bit Pentium III, I get no warnings when 
> compiling your test program, even with -Wall. When it runs, 0 gives the 
> same result as 32, so it overflows (silently) on my machine.

Ooh, here's something interesting.  I first tried a test with constants,
and got the warning: left shift count >= width of type" out of gcc.
Then I rewrote the thing to use a loop, and I got correct results out of
it.  (This is all on an Athlon64X2.)

When you described getting the same results for 0 and 32, I tried it
again on my wife's laptop, a Celeron M, and got the same results you
did; just out of curiosity, I looked it up, and gcc generates a 'sall'
instruction to do the actual bit-shift, which on the 80386, PIII and
Celeron M (according to Intel's documentation, your test, and my test,
respectively) all ignore everything but the low 5 bits on the shift
count.  The 64-bit Athlon64 apparently doesn't, though, even though I'm
supposedly running in 32-bit compatibility mode.  Huh.

Yet another demonstration of the dangers of of assuming specific
bit-sizes for int, I suppose.

_______________________________________________
gnhlug-discuss mailing list
gnhlug-discuss@mail.gnhlug.org
http://mail.gnhlug.org/mailman/listinfo/gnhlug-discuss

Reply via email to