2 * Copyright 2011-2012 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 \n]*")) {
45 ASN1IllegalArgument ex = new ASN1IllegalArgument();
46 ex.setMessage("Invalid string '" + string
47 + "'. hString must consist of hexadecimal string.", null,
51 StringBuilder builder = new StringBuilder();
52 for (char c: string.toCharArray()) {
53 if (Character.digit(c, 16) >= 0) {
57 this.string = builder.toString().trim().toUpperCase();
61 * Instantiates a {@code HexString} and initialize it with an array of
65 * The array of {@code byte}.
67 public HexString(byte... array) {
68 StringBuilder builder = new StringBuilder();
69 for (Byte b : array) {
70 builder.append(String.format("%02X", b));
72 string = builder.toString();
76 * Returns the string value of this hString.
78 * @return The hexadecimal string.
80 public String string() {
85 * Converts the value of this hString to an array of {@code boolean}.
87 * @return An array of {@code boolean}.
89 public boolean[] toBinArray() {
90 boolean[] array = new boolean[string.length() * 4];
91 int index = 0, mask = 0;
93 for (int i = 0; i < array.length; i++) {
95 octet = Byte.parseByte(string.substring(index++, index), 16);
98 array[i] = (octet & mask) > 0;
105 * Converts the value of this hString to an array of {@code byte}.
107 * @return An array of {@code byte}.
109 public byte[] toByteArray() {
110 byte[] array = new byte[string.length() / 2 + string.length() % 2];
112 for (int i = 0; i < string.length(); i++) {
113 octet = Integer.valueOf(string.substring(i, i + 1), 16).byteValue();
115 array[i / 2] = (byte) (octet << 4);
117 array[i / 2] = (byte) (array[i / 2] + octet);
124 * Returns a string representation of this item.
126 * @return A string representation of this item.
129 public String toString() {
130 return '\'' + string + "\'H";