bits wrap when leftshifting non-constant amounts

deeptech71 at gmail.com deeptech71 at gmail.com
Tue Feb 12 17:43:43 PST 2008


My gcc 3.4.6 behaves weirdly when left shifting, and I couldn't find any 
info on this.

the program:
#include <stdio.h>
int main( void ) {
	unsigned n;
	for( n = 13; n < 100; n += 7 ) {
		printf( "0x42f1u << %u = %u\n", n, 0x42f1u << n );
	}
	return 0;
}


the output:
0x42f1u << 13 = 140386304
0x42f1u << 20 = 789577728
0x42f1u << 27 = 2281701376
0x42f1u << 34 = 68548
0x42f1u << 41 = 8774144
0x42f1u << 48 = 1123090432
0x42f1u << 55 = 2021654528
0x42f1u << 62 = 1073741824
0x42f1u << 69 = 548384
0x42f1u << 76 = 70193152
0x42f1u << 83 = 394788864
0x42f1u << 90 = 3288334336
0x42f1u << 97 = 34274

When I left shift a constant amount, it works. That is:
     ( 1u << 34u ) == 0

But using a variable:
     unsigned lsh = 34;
     ( 1u << lsh ) == 4 !!!

It seems that lsh is first moduloed with the width of int. What the hell?


More information about the freebsd-chat mailing list