tags:

views:

2904

answers:

5

Hi i'm reading 133 length packet from serialport,last 2 bytes contain CRC values,2 bytes value i've make 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 correct result,is it problem because signed valued? how can i solve this problem,plz help me i'm in trouble

A: 

EDIT: If your variable is a byte, you can't shift by 8. Do:

(high << 7 << 1) + low;

EDIT: If you don't want the sign extend. Do:

int high = (-48 & 0x00ff);
int c = (high << 8) + low;

signed -12208 = unsigned 53328, same bits: 1101 0000 0101 0000 So go to the data type that is larger so the sign won't extend.

CookieOfFortune
ya i have done but then also i'm not getting correct result
result is -12208
i want 53328 as a result
i've done (high << 7 << 1) + low;still same result
yes i got the answer thank u very much
There's nothing wrong with shifting a byte value by 8 as it gets converted to an int before the shift.
starblue
+8  A: 

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.

Neil Coffey
you're right, it does promote to int so shift by 7 is ok. But << 32 is undefined so it does nothing.
CookieOfFortune
A: 

When converting byte values from a stream into numeric values in Java you have to be very careful with sign extension. There is a trap with negative numbers (values from (unsigned) 128-255).

Try this (it works if hi and lo are any Java integer type) :

short val=(short)( ((hi&0xFF)<<8) | (lo&0xFF) );

I find it's best to be explicit with the parentheses in these cases.

Software Monkey
starblue
A: 

Hi

I am new to java programming. Does anyone know how can I assign 2 bytes to variable.

for example byte val = 2; // this is one byte with 0000 0010 but i need to assign 2 bytes to val....(val is 2 bytes long)..

Any sort of help is appreciated. Thanks in advance.

Kam

Kam
We would be glad to help, but please look at your own question and clarify it a bit.
kd304
+1  A: 

The other answers are OK, but I would like to put an emphasis on the type:

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

int c= ((high & 0xFF) << 8) | (low & 0xFF);

The short type can represent values between -32768 to 32767. 53328 cannot be nicely stored in short, use int instead as it allows you to store unsigned value up to ~109 So don't downcast the expression to short as it will net you the signed value.

kd304