Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Loop by bit shift

Status
Not open for further replies.

sroberts82

Programmer
Oct 11, 2005
36
US
Hi
I want to do a for loop by bit shift, so I loop through 0,1,2,4,8 etc... 0,1,10,100,1000 etc
So I did this:

for(int i =0x1; i<100; i = i<<1)
{
//do stuff
}

Thats fine, but it leaves out zero. I can't start at zero cos a bit shift on zero is zero. I was thinking if I cut off the least significant bit of i I would get what I want...but I don't know how to do that. Can someone help?
Thanks
 
What is wrong with handling case 0 outside the loop, then all other cases with the loop?


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
You could put this at the end of the loop:
Code:
if ( i == 0 )
{
   i = 1;
}
 
Are you allowed to do it backwards?
Code:
ii = 0x10000; // Must be 1 bit more than required
do {
   ii >>= 1;
   ...
} while (ii != 0);
That will do 0x8000 through to 0.
 
Or you could do exactly as you said: loop from 1 upwards, and make use of that value shifted one place to the right inside the loop.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top