Reputation: 1103
I have a TCP packet that sends a bunch of unsigned variables (they are unsigned because they are saving space and using the limits for unique IDs), I need to convert this unsigned short bit data into an Integer in java.
So my question is how do I convert byteArray[0 - 15] into an int?
Edit:
Here is the code I have changed to:
ByteOrder order = ByteOrder.BIG_ENDIAN;
requestedDateType = new BigInteger(ByteBuffer.allocate(2).put(data, 8, 2).order(order).array()).intValue();
The data buffer coming in is:
bit 0 1 2 3 4 5 6 7 8 9
value 40 0 0 0 8 0 0 0 1 0
The data is sent as Little Endian. I assume since BigInteger assumes big, I need to convert to that. However both big or little Order give me the same value in return.
I expect to get 1 for the value of requestedDateType
however I am getting 256. How do I pad the two missing bytes to make sure it gives me 0000 0000 0000 0001 instead of 0000 0001 0000 0000
Edit 2:
Never mind. Changed code to this:
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(data, 8, 2);
int value = ((int)bb.getShort(0)) & 0xff;
Upvotes: 0
Views: 1250
Reputation: 1103
I ended up utilizing this resource: http://www.javamex.com/java_equivalents/unsigned.shtml
ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(data, 8, 2);
requestedDateType = ((int)bb.getShort(0)) & 0xff;
I copied the two bytes into a short, then converted it into an int and removed the sign.
Upvotes: 0
Reputation: 11006
Use ByteBuffer in the java.nio package.
//Convert unsigned short to bytes:
//java has no unsigned short. Char is the equivalent.
char unsignedShort = 100;
//Endianess of bytes. I recommend setting explicitly for clarity
ByteOrder order = ByteOrder.BIG_ENDIAN;
byte[] ary = ByteBuffer.allocate(2).putChar(value).order(order).array();
//get integers from 16 bytes
byte[] bytes = new byte[16];
ByteBuffer buffer= ByteBuffer.wrap(bytes);
for(int i=0;i<4;i++){
int intValue = (int)buffer.getInt();
}
Guava also has routines for primitive to byte conversion if you're interested in an external library: http://code.google.com/p/guava-libraries/
Also, I don't know your use-case, but if you're in the beginning stages of your project, I'd use Google's ProtoBufs for exchanging protocol information. It eases headaches when transitioning between protocol versions, produces highly compact binary output, and is fast.
Also if you ever change languages, you can find a protobufs library for that language and not rewrite all your protocol code.
http://code.google.com/p/protobuf/
Upvotes: 4