# Thread: Need Help Urgent - Bit level operation

1. Member
Join Date
Feb 2011
Posts
4
Rep Power
0

## Need Help Urgent - Bit level operation

Hi I have the following requirement:

I have to find the position of the higher order bit for a given number. I am achiving it by the following method.

for (int key = 0; key<32; key++)
{
result = ((given_number & 0x80000000) == 0) ? 0 : 1;
system.out.println(result);
given_number<<=1;
}

This works fine when the given_value is of type int.

For long it doesnt work at all.

Ex. if given value is 1048576, I get the posiotn of 1 to be 11.
when i print this, 00000000000100000000000000000000

But if i initiliaze 1048576 as long, it doesnt work.
When i print this 00000000000111111111111111111111

2. Since it is urgent I'll get back to you tomorrow.

3. Member
Join Date
Feb 2011
Posts
4
Rep Power
0
I tried with 0x8000000000000000l , and now i am getting 00000000000000000000000000000000.....

4. I don't want to spoon feed it to you. Let me see if I can suggest a way to bring you around to the right conclusion:

Rather than masking with 0x80000000, what would you expect to get if you just masked with '1' ?

Also, rather than shifting left, what happens if every loop you shift right? >>>= (yes, you need 3 of them).

Also Also, if you print this using my suggestions, is it forward or backwards? How could you reverse it if its backwards?

Finally, do you know why you are counting to 32 in your loop? How high would you count for a long?

5. Member
Join Date
Jan 2011
Posts
9
Rep Power
0
Hey:
I'm not sure I'm understanding you right, but why don't you mask with a 64 bit number, i.e. with 0x8000000000000000 ?
You have to know the type of variable in your function so you can select the corresponding mask to use, well, that is, unless you're using templates and don't know what variable type it is.

6. Member
Join Date
Feb 2011
Posts
4
Rep Power
0
Hi thanks a TON everyone!,

I used the following logic,

for (int key = 0; key<64; key++)
{
pr = ((number_toFind & 0x8000000000000000l) == 0) ? 0 : 1; //get value of leftmost bit

and it worked!!! Thanks a lot again:)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•