Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to cram two bytes into a short?

800306Jul 24 2007 — edited Jul 25 2007

Hi all,

I have some byte[] data that I am receiving, and I need to put two bytes into one short (or int, or whatever), as the byte[] will form a two bytes-per-pixel image. I've been working with 8-bit data (this is 12-bits, NOT packed), which is much easier to manipulate.

I currently have this method to convert a byte[] of 8-bit data into a short (I do this because Java does not support signed types and I need that 8th bit):

private short[] convertBytesToShorts(byte[] data) {
	short[] convertedData = new short[data.length];
	for (int i = 0; i < data.length; i++) {
		convertedData[i] = (short)((short)data[i] & 0xff);
	}
	return convertedData;
}

Is there a way to modify this to place two bytes into one short? Is it possible to just AND two bytes with 0xff and add them together to create one short? Surely it cannot be that simple. Also, remember that I must treat the values as unsigned.

Furthermore, the two bytes look like this:

| xxxx xxxx | xxxx 0000 |

So the last four bits in the second byte are 0s.

Any advice is appreciated.

Message was edited by:
Djaunl

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 22 2007
Added on Jul 24 2007
26 comments
1,354 views