01: package com.mockrunner.example.connector;
02:
03: import java.io.UnsupportedEncodingException;
04:
05: /**
06: * Helper class to convert Java types to commarea bytes and back.
07: */
08: public class Marshaller {
09: public static byte[] marshalString(String data, int size) {
10: if (null == data)
11: data = "";
12: if (data.length() > size)
13: data = data.substring(0, size);
14: StringBuffer buffer = new StringBuffer(data);
15: for (int ii = buffer.length(); ii < size; ii++) {
16: buffer.append(" ");
17: }
18: try {
19: return buffer.toString().getBytes("Cp273");
20: } catch (UnsupportedEncodingException exc) {
21: exc.printStackTrace();
22: }
23: return new byte[size];
24: }
25:
26: public static String unmarshalString(byte[] data) {
27: try {
28: return new String(data, "Cp273");
29: } catch (UnsupportedEncodingException exc) {
30: exc.printStackTrace();
31: }
32: return "";
33: }
34:
35: public static byte[] marshalNumber(int number) {
36: return new byte[] { (byte) ((number >> 24) & 0xFF),
37: (byte) ((number >> 16) & 0xFF),
38: (byte) ((number >> 8) & 0xFF), (byte) (number & 0xFF) };
39: }
40:
41: public static int unmarshalNumber(byte[] data) {
42: int shiftBits = (data.length - 1) * 8;
43: int result = 0;
44: for (int ii = 0; ii < data.length; ii++) {
45: result |= ((0xFF & (int) data[ii]) << (shiftBits - (ii * 8)));
46: }
47: return result;
48: }
49: }
|