001 package toolbus.util; 002 003 /** 004 * This class handles the conversion of native types from and to their byte representation. 005 * 006 * @author Arnold Lankamp 007 */ 008 public class NativeTypeConverter{ 009 private final static int BYTEMASK = 0xFF; 010 011 /** 012 * Default constructor. Made private to prevent instantiation. 013 */ 014 private NativeTypeConverter(){ 015 super(); 016 } 017 018 /** 019 * Merges two (little endian encoded) bytes into a unsigned short value. 020 * 021 * @param shortBytes 022 * The two (little endian encoded) bytes. 023 * @return The resulting short value. 024 */ 025 public static int makeUnsignedShort(byte[] shortBytes){ 026 return (shortBytes[0] & BYTEMASK) | ((shortBytes[1] & BYTEMASK) << 8); 027 } 028 029 /** 030 * Splits the given unsigned short value into two separate bytes (little endian encoded). 031 * 032 * @param twoByteNumber 033 * The short that needs to be split. 034 * @return Two (little endian encoded) bytes. 035 */ 036 public static byte[] makeBytesFromUnsignedShort(int twoByteNumber){ 037 byte[] shortBytes = new byte[2]; 038 039 shortBytes[0] = (byte) (twoByteNumber); 040 shortBytes[1] = (byte) (twoByteNumber >>> 8); 041 042 return shortBytes; 043 } 044 045 /** 046 * Merges four (little endian encoded) bytes into a int value. 047 * 048 * @param intBytes 049 * The four (little endian encoded) bytes. 050 * @return The resulting int value. 051 */ 052 public static int makeInt(byte[] intBytes){ 053 return (intBytes[0] & BYTEMASK) | ((intBytes[1] & BYTEMASK) << 8) | ((intBytes[2] & BYTEMASK) << 16) | ((intBytes[3] & BYTEMASK) << 24); 054 } 055 056 /** 057 * Splits the given int value into four separate bytes (little endian encoded). 058 * 059 * @param fourByteNumber 060 * The int that needs to be split. 061 * @return Four (little endian encoded) bytes. 062 */ 063 public static byte[] makeBytesFromInt(int fourByteNumber){ 064 byte[] intBytes = new byte[4]; 065 066 intBytes[0] = (byte) fourByteNumber; 067 intBytes[1] = (byte) (fourByteNumber >>> 8); 068 intBytes[2] = (byte) (fourByteNumber >>> 16); 069 intBytes[3] = (byte) (fourByteNumber >>> 24); 070 071 return intBytes; 072 } 073 }