Sunday, June 17, 2012

Java: Short to Bytes

Here's how to do it:


public static byte[] shortToBytes(short theShort) {
   byte[] theBytes = new byte[2];
   theBytes[0] = (byte)((theShort >> 8) & 255);
   theBytes[1] = (byte)(theShort & 255);

   return theBytes;
}

The purpose of the "& 255" bitwise operator is to ensure that all bits before the last byte are 0.

No comments:

Post a Comment