//Code example for manipulating binary data import java.lang.*; import java.util.*; public class CityRec { // definition of a city record private int x; private int y; private String name; public CityRec(int inx, int iny, String inname) /* constructor 1: specify x, y and name */ { x=inx; y=iny; name=inname; } public CityRec(byte record[]) /* constructor 2: specify a byte array record with the first byte containing the length, followed by x, y and name */ { x = ((int) (record[1] & 0xFF) << 24) + ((int) (record[2] & 0xFF) << 16) + ((int) (record[3] & 0xFF) << 8 )+ ((int) (record[4] & 0xFF) << 0 ); y = ((int) (record[5] & 0xFF) << 24) + ((int) (record[6] & 0xFF) << 16) + ((int) (record[7] & 0xFF) << 8 )+ ((int) (record[8] & 0xFF) << 0 ); name = new String(record, 9, (int)record[0] - 9); } public int x() { return x;} public int y() { return y;} public String name() { return name;} public byte[] getRecord(){ // compose a byte array record out of this CityRec object //reclength will be the sum of the sizes of x, y, name plus 1 int reclength = 8 + name.length()+1; byte[] record=new byte[reclength]; // defining the byte array //store x; record[0] = (byte)reclength; record[1] = (byte)(x >> 24); record[2] = (byte)(x >> 16); record[3] = (byte)(x >> 8); record[4] = (byte)(x >> 0); //store y; record[5] = (byte)(y >> 24); record[6] = (byte)(y >> 16); record[7] = (byte)(y >> 8); record[8] = (byte)(y >> 0); //store name; for(int i=0; i < name.length(); i++) record[9+i] = (byte)(name.charAt(i)); return record; } public static void main(String[] args) { int inx = 1000; int iny = 2038; String inname = "Falls Church"; CityRec a= new CityRec(inx, iny, inname); //check this CityRec object System.out.println("check the CityRec object: "); System.out.println("X coord: "+a.x()); System.out.println("Y coord: "+a.y()); System.out.println("Name: "+a.name()); System.out.println(); // convert the CityRec object into the byte array object format byte[] aRecord=a.getRecord(); // check record System.out.println("check the byte array record: "); System.out.println("record length: "+Byte.toString(aRecord[0])); //convert the byte array object into the CityRec object format CityRec b = new CityRec(aRecord); System.out.println("X coord: "+b.x()); System.out.println("Y coord: "+b.y()); System.out.println("Name: "+b.name()); } // end main }