Sign in to follow this  
Ksingh30

low level C

Recommended Posts

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this