• Post Reply Bookmark Topic Watch Topic
  • New Topic

Binary - Bit level Operations  RSS feed

 
Uday Bhagwat
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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........
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please UseCodeTags next time, that will make it a bit easier to read your code.

To get the value of the left-most bit, you need a bit mask of 1000 000 for byte, 1000 0000 0000 0000 for short, 1000 0000 0000 0000 0000 0000 0000 0000 for int and 1000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 for long. The good thing is, you don't need to write them as such. You can use the bitwise operators to get those numbers:
1 << 7 (the size of byte is 8 so subtract one)
1 << 15 (the size of short is 16 so subtract one)
1 << 31 (the size of int is 32 so subtract one)
1L << 63 (the size of long is 64 so subtract one; the L is to make the result long instead of int)

Alternatively, you can use 1 << -1 for int and 1L << -1 for long. That's because the number to shift by is modulo 32 for int and modulo 64 for long.
 
Uday Bhagwat
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi thanks a TON Rob!,

I used the following logic,


and it worked Thanks again!!!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would prefer to write 1L << -1 instead to be honest. It's the same as 0x8000000000000000L* but it's easier to read. I don't recognize 0x8000000000000000L as easily as I recognize 1L << -1 or 1L << 63. And I don't think I'm the only one.


* never ever ever use a lowercase l to indicate a number is a long! Always use uppercase L. It's too easy to misread the l as a 1. My first thought in this reply was to ask you if that 1 at the end of 0x8000000000000000l was a mistake or not. Then I found out it was an l.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aren't there ready-made Integer class methods which do that sort of thing?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!