biddulph.r
biddulph.r

Reputation: 5266

Bitshifting to read/write data

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!

Upvotes: 0

Views: 100

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533680

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()

Upvotes: 0

Bombe
Bombe

Reputation: 83928

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.

Upvotes: 1

Related Questions