Subversion Repositories Code-Repo

Compare Revisions

Ignore whitespace Rev 92 → Rev 93

/Classwork/CS3114/Project 1/ByteStringConverter.java
0,0 → 1,40
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;
}
}