Alex Rivera | Logout

2 bytes to short

Asked 2009-04-10T05:45:34.607
36

I'm reading a packet with a length of 133 bytes from the serialport, the last 2 bytes contain the CRC values, 2 byte values I've made single (short I think) using Java.

This what I have done:

short high = (-48 & 0x00ff);
short low = 80;

short c = (short) ((high << 8) + low);

But I'm not getting the correct result. Is it a problem because of the use of signed values? How can I solve this problem?

Edit
Report

1 Answer

69

Remember, you don't have to tie yourself in knots with bit shifting if you're not too familiar with the details. You can use a ByteBuffer to help you out:

ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.put(firstByte);
bb.put(secondByte);
short shortVal = bb.getShort(0);

And vice versa, you can put a short, then pull out bytes.

By the way, bitwise operations automatically promote the operands to at least the width of an int. There's really no notion of "not being allowed to shift a byte more than 7 bits" and other rumours that seem to be going round.

answered 2009-04-10T06:06:09.907

Your Answer