Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assembling a 16 bit short from two bytes

Status
Not open for further replies.

dbrb2

Instructor
Jul 19, 2004
121
GB
Hi,

I'm receiving two bytes across a serial link (from a PIC ucontroller). They are interpreted as 2s complement and stored in an integer variable. The two bytes are in fact the high and low bytes of a 16bit value, and I want to reconstruct them as such when they arrive.

I assume I need to cast the int to a byte, then use binary shift operators somehow, but am getting a bit stuck - any help would be wonderful.


Cheers,


Ben
 
Take the high byte and multiply by 256. Then add the low byte.

Bob Rashkin
rrashkin@csc.com
 
Something like :-

Code:
int fullInt = (highByte & 255) * 256 + (lowByte & 255);

where highByte is your Most Significant int and lowByte is your least Significant one.

Tim
 
Another way:

Code:
java.math.BigInteger bg = new java.math.BigInteger(new byte[] {byte1,byte2);
bg.intValue()

Cheers,

Dian
 
Thanks! I take it the highByte & 255 line is equivalent to
(byte)highbyte - i.e forcing java to cast the int to a byte?


Ben
 
No. If you cast the input ints to bytes, you get two's compliment results, eg. (byte)255 gives -1.

The highByte & 255 is an 8 bit mask. It simply returns the bottom 8 bits of the highByte int.

Tim
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top