Sunday, June 17, 2012

Java: Bytes to Short

Here is how to convert bytes to short in Java, with a function to prove/test it:


private static short bytesToShort(byte[] theBytes) {
   short msb = theBytes[0];
   short lsb = (short)(theBytes[1] & 255);
   msb = (short)(msb << 8);
       
   short result = (short)(msb | lsb);
   return result;
}
// for testing the bytesToShort functionpublic static void main(String[] args) throws Exception {
   int numValues = Short.MAX_VALUE - Short.MIN_VALUE + 1;
   short[] testValues = new short[numValues];
   for (int i = 0; i < testValues.length; i++) {
       testValues[i] = (short)(Short.MIN_VALUE + i);
   }
   int numWrongAnswers = 0;
   for (int i = 0; i < testValues.length; i++) {
       ByteArrayOutputStream bos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(bos);
       dos.writeShort(testValues[i]);
       byte[] theBytes = bos.toByteArray();
       short s = bytesToShort(theBytes);

       String correct = "";
       if(s == testValues[i]){
               correct = "yes";
       }
       else {
               numWrongAnswers++;
               correct = "NO!!!!!!!!!!!";
       }
       System.out.println("original: " + testValues[i] + " converted: " + s + " OK? " + correct);
       }
       System.out.println("numWrongAnswers: " + numWrongAnswers);
}

No comments:

Post a Comment