Subversion Repositories Code-Repo

Rev

Rev 93 | Blame | Compare with Previous | Last modification | View Log | RSS feed

import java.nio.ByteBuffer;

// Assisting class for MemClient to convert values to a byte array and vice versa
public class ByteStringConverter {
        // Converts the passed string array into a byte array
        public static byte[] convertToByteArray(int int1, int int2, String str) {
                // Use ByteBuffer to serialize to bytes
                byte[] byteArray = new byte[8 + str.length()];
                byte[] bstr = str.getBytes();
                
                ByteBuffer buffer = ByteBuffer.wrap(byteArray);
                
                // Insert passed values into the byte array
                buffer.putInt(int1);
                buffer.putInt(int2);
                buffer.put(bstr);
                
                return byteArray;
        }

        // Converts the byte array into a string array
        public static String[] convertToStringArray(byte[] byteArray) {
                // Array of values to return from byte array
                String[] strArray = new String[3];
                
                ByteBuffer buffer = ByteBuffer.wrap(byteArray);
                
                int int1 = buffer.getInt();
                int int2 = buffer.getInt();
                byte[] bstr = new byte[byteArray.length - 8];
                buffer.get(bstr);
                
                // Pull values from byte array into string array
                strArray[0] = Integer.toString(int1);
                strArray[1] = Integer.toString(int2);
                strArray[2] = new String(bstr);
                
                return strArray;
        }
}