01: package gnu.kawa.xml;
02:
03: /** A BinaryObject whose lexical format is hexBinary. */
04:
05: public class HexBinary extends BinaryObject {
06: public HexBinary(byte[] data) {
07: this .data = data;
08: }
09:
10: static HexBinary valueOf(String str) {
11: return new HexBinary(parseHexBinary(str));
12: }
13:
14: static byte[] parseHexBinary(String str) {
15: str = str.trim();
16: int len = str.length();
17: if ((len & 1) != 0)
18: throw new IllegalArgumentException(
19: "hexBinary string length not a multiple of 2");
20: len = len >> 1;
21: byte[] result = new byte[len];
22: for (int i = 0; i < len; i++) {
23: int d1 = Character.digit(str.charAt(2 * i), 16);
24: int d2 = Character.digit(str.charAt(2 * i + 1), 16);
25: int bad = -1;
26: if (d1 < 0)
27: bad = 2 * i;
28: else if (d2 < 0)
29: bad = 2 * i + 1;
30: if (bad >= 0)
31: throw new IllegalArgumentException(
32: "invalid hexBinary character at position "
33: + bad);
34: result[i] = (byte) (16 * d1 + d2);
35: }
36: return result;
37: }
38:
39: static char forHexDigit(int val) {
40: return val < 10 ? (char) (val + '0') : (char) (val - 10 + 'A');
41: }
42:
43: public StringBuffer toString(StringBuffer sbuf) {
44: byte[] bb = data;
45: int len = bb.length;
46: for (int i = 0; i < len; i++) {
47: byte b = bb[i];
48: sbuf.append(forHexDigit((b >> 4) & 15));
49: sbuf.append(forHexDigit(b & 15));
50: }
51: return sbuf;
52: }
53:
54: public String toString() {
55: return toString(new StringBuffer()).toString();
56: }
57: }
|