• Advertisement
Sign in to follow this  

low level C

This topic is 4103 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

lets say I hav a 32 bit int x which holds the value 5 currently so its 0.....0101 how can I get it to print the left most one in 101

Share this post


Link to post
Share on other sites
Advertisement
What do you mean by "print the leftmost one"? Do you want to find the index of the leftmost one, or just print a '1' if there is one in the number?

Share this post


Link to post
Share on other sites
If you always want to print just bit 2 (bits are numbered from 0, starting at the right) then you're looking for the following:

printf("%d", (x >> 2) & 0x1);

I'm assuming you're familiar with printf.

The (x >> 2) evaluates to the number in x bitshifted to the right by two digits. The bitwise AND operation (& 0x1) with 1 means that this essentially evaluates to the lowest bit of this now shifted number. To demonstrate (not written as 32-bits, because life's too short, but you get the idea):


1111 1111 ... Starting off
0111 1111 ... Shift right once
0011 1111 ... Shift right twice

Now that the digit originally in bit 2 is now in bit 0, we can do a
bitwise AND to return it.

0011 1111
AND 0000 0001
0000 0001


Hopefully you can see how this works and tweak it as appropriate.

EDIT: Although this should give you the principles (bitmasking is the general name for this, btw) required for whatever it is you're trying to do, I doubt it is exactly what you're trying to do (because I can't see much reason for wanting to do this unless you're storing a bunch of flags in a single 32 bit).

Share this post


Link to post
Share on other sites
I'm guessing you are trying to print all digits to the right of the leftmost 1?

In that case, you could do something like

unsigned int tmp = 0x80000000;
while(!(x & tmp))tmp >>= 1;
while(tmp)
{
printf("%d",x & tmp);
tmp >>= 1;
}


I did not test this code and don't know if it should work, but whatever..

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement