Serving the Quantitative Finance Community

 
User avatar
countblessings
Topic Author
Posts: 0
Joined: June 7th, 2012, 11:05 am

Odd Numbers

August 17th, 2012, 9:21 pm

Why would this code print out odd numbers between 1 to 11? for ( unsigned int i = 1; i <= 100; i++ ) { if( i& 0x00000001 ) { cout << i<< endl; }; }
 
User avatar
Hansi
Posts: 41
Joined: January 25th, 2010, 11:47 am

Odd Numbers

August 17th, 2012, 9:41 pm

Does all odd numbers up to 100 actually.0x00000001 -> binary 1& -> bitwise AND operatori & 0x00000001 converts the binary representation of i to zero excluding the last bit.E.g.1 0000000000000001 0000000000000001 true2 0000000000000010 0000000000000000 false3 0000000000000011 0000000000000001 true4 0000000000000100 0000000000000000 false
Last edited by Hansi on August 16th, 2012, 10:00 pm, edited 1 time in total.
 
User avatar
Traden4Alpha
Posts: 3300
Joined: September 20th, 2002, 8:30 pm

Odd Numbers

August 17th, 2012, 9:44 pm

i & 0x00000001 returns 0x00000000 if i is even and returns 0x00000001 if i is odd. That i & 0x00000001 basically pulls off the LSB of i.