2 * Copyright 2011 BitMeister Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package jp.bitmeister.asn1.value;
18 import jp.bitmeister.asn1.exception.ASN1IllegalArgument;
21 * Represents ASN.1 'Hex string(hString)' item.
24 * An instance of this class represents a 'hString' item.
27 * @author WATANABE, Jun. <jwat at bitmeister.jp>
29 public class HexString implements StringItem {
32 * The hexadecimal string.
34 private String string;
37 * Instantiates a {@code HexString} and initialize it with a {@code String}.
40 * The {@code String} that consist of an arbitrary numbers of
41 * hexadecimal characters.
43 public HexString(String string) {
44 if (!string.matches("[0-9A-Fa-f]*")) {
45 ASN1IllegalArgument ex = new ASN1IllegalArgument();
46 ex.setMessage("Invalid string '" + string
47 + "'. hString must consist of hexadecimal string.", null,
51 this.string = string.trim().toUpperCase();
55 * Instantiates a {@code HexString} and initialize it with an array of
59 * The array of {@code byte}.
61 public HexString(byte... array) {
62 StringBuilder builder = new StringBuilder();
63 for (Byte b : array) {
64 builder.append(String.format("%02X", b));
66 string = builder.toString();
70 * Returns the string value of this hString.
72 * @return The hexadecimal string.
74 public String string() {
79 * Converts the value of this hString to an array of {@code boolean}.
81 * @return An array of {@code boolean}.
83 public boolean[] toBinArray() {
84 boolean[] array = new boolean[string.length() * 4];
85 int index = 0, mask = 0;
87 for (int i = 0; i < array.length; i++) {
89 octet = Byte.parseByte(string.substring(index++, index), 16);
92 array[i] = (octet & mask) > 0;
99 * Converts the value of this hString to an array of {@code byte}.
101 * @return An array of {@code byte}.
103 public byte[] toByteArray() {
104 byte[] array = new byte[string.length() / 2 + string.length() % 2];
106 for (int i = 0; i < string.length(); i++) {
107 octet = Integer.valueOf(string.substring(i, i + 1), 16).byteValue();
109 array[i / 2] = (byte) (octet << 4);
111 array[i / 2] = (byte) (array[i / 2] + octet);
118 * Returns a string representation of this item.
120 * @return A string representation of this item.
123 public String toString() {
124 return '\'' + string + "\'H";