Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get a 42 bit long number in Java.  RSS feed

 
Ashish Schottky
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java's long comprises of 63 bits where in the MSB is stored for the sign.

I want to set 42nd bit of a particular number as 1.
So I tried 1<<42, however this doesnt give the output as what I thought.
neither did this work 1<<(42L).
I am not supposed to use Strings and other wrapper class functions.
Is there anyway by which I can fix this up? This is a small part of my program but a vital one.
I am getting the answer to be 1024, this very well means that it is treating it to be a 32 bit number and then 1<<10.
confused with this.
-Thank you.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What did you get, and what did you expect? and please post your actual code (in code tags) so we can see what you are REALLY doing.

I have a few guesses as to what the problem may be, but without seeing what you're doing, and knowing what you are expecting, they would only be guesses.

edit: I believe the problem is with your '1' literal. try declaring it as a long :

1L << 42

also.... the set bit is already in the first position, so you may need to only shift it 41.

 
Ashish Schottky
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Fred
Thanks for reply.
Well I am writing this independently and once I get this part working I will integrate it with my code.

I was expecting 4398046511104
where as I got 1024.
Edit after you edited:
Thanks a lot it solved my problem.
 
Paul Clapham
Sheriff
Posts: 22502
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was going to make a suggestion, but I see Fred has already made that suggestion. So now my suggestion is to read and implement Fred's suggestion.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashish Schottky wrote:
Thanks a lot it solved my problem.

More importantly, do you understand WHY it solved your problem?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!