I am sending 2 integers as one long in Java, and cannot work out for the life of me how to send these across properly using bit shifting.
I have a method to create the long:
public long create(int one, int two){
return (one <<32 & two);
}
First of all, is this correct? (To send the two integers in one long together)
Secondly, if I want to then access either one or two, how do I go about that?
Is it a simple case of:
public static int getOne(long theLong) {
return (int)theLong >> 32;
开发者_运维问答 }
Or is there something a little more complicated?
Some guidance is much appreciated, thanks!
When shifting an int
value the second operator (the shift width) is &
’ed with 31, so someInt << 32
is someInt
. Cast your int
to long
before shifting: (long) someInt << 32
, this will now give the result you expected.
Try
public long create(int one, int two){
return ((long) one << 32) | (two & 0xFFFFFFFFL);
}
The way you are sending the data should support multiple int
values if it supports long
e.g. for DataOuput
uses writeInt()
instead of writeLong()
精彩评论