Results 1 to 7 of 7
- 02-11-2011, 05:19 AM #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
Please help........
- 02-11-2011, 05:29 AM #2
Since it is urgent I'll get back to you tomorrow.
- 02-11-2011, 06:11 AM #3
Member
- Join Date
- Feb 2011
- Posts
- 4
- Rep Power
- 0
I tried with 0x8000000000000000l , and now i am getting 00000000000000000000000000000000.....
Please help....
- 02-11-2011, 06:18 AM #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?
- 02-11-2011, 09:21 AM #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.
- 02-11-2011, 10:18 AM #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:)
- 02-11-2011, 02:00 PM #7
Similar Threads
-
Top level and member level
By Differintegral in forum New To JavaReplies: 1Last Post: 07-30-2010, 03:50 AM -
XOR operation on bytes
By divyanshu023 in forum New To JavaReplies: 1Last Post: 09-17-2009, 07:11 PM -
Bit Wise operation: shifting
By rueter in forum New To JavaReplies: 1Last Post: 06-27-2009, 06:51 AM -
[SOLVED] Class-level vs Object-level method()
By mfaizan24 in forum New To JavaReplies: 7Last Post: 06-23-2009, 09:18 AM -
Frame close operation
By Java Tip in forum Java TipReplies: 0Last Post: 12-21-2007, 08:39 AM
Bookmarks