[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Byte Arrays



I need to encode bytes into a ByteArrayOutputStream.  The data in each byte must be exactly eight bits long without truncating the leading zeros.  For example, if I want to encode the integer value 12 (as an unsigned byte) I am doing the following:

 

ByteArrayOutputStream out = new ByteArrayOutputStream();

short num = 12;

out.write(num & 0xFF);

 

However, if I read the first element in the ByteArrayOutputStream into a string variable, the leading zeros are truncated, leaving only 1100.

 

The communication protocol that we are using expects a single octet with the leading zeros left in, or else the framing will be off.  How do I maintain the zero placeholders in each byte and keep them from being truncated?  Or am I missing something here?

 

Greg Lusk