# Need Help Urgent - Bit level operation

• 02-11-2011, 06:19 AM
uday.bhagwat7
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

• 02-11-2011, 06:29 AM
Junky
Since it is urgent I'll get back to you tomorrow.
• 02-11-2011, 07:11 AM
uday.bhagwat7
I tried with 0x8000000000000000l , and now i am getting 00000000000000000000000000000000.....

• 02-11-2011, 07:18 AM
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?
• 02-11-2011, 10:21 AM
mattie
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.
• 02-11-2011, 11:18 AM
uday.bhagwat7
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:)
• 02-11-2011, 03:00 PM