bits wrap when leftshifting non-constant amounts

看板FB_chat作者時間18年前 (2008/02/13 09:44), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/3 (看更多)
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? _______________________________________________ freebsd-chat@freebsd.org mailing list http://lists.freebsd.org/mailman/listinfo/freebsd-chat To unsubscribe, send any mail to "freebsd-chat-unsubscribe@freebsd.org"
文章代碼(AID): #17iaj-00 (FB_chat)
文章代碼(AID): #17iaj-00 (FB_chat)