1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17 package android.carrierapi.cts; 18 19 import javax.annotation.Nonnull; 20 21 /** Utility class for converting between hex Strings and bitwise representations. */ 22 public class IccUtils { 23 24 // A table mapping from a number to a hex character for fast encoding hex strings. 25 private static final char[] HEX_CHARS = { 26 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 27 }; 28 29 @Nonnull bytesToHexString(byte[] bytes)30 public static String bytesToHexString(byte[] bytes) { 31 StringBuilder ret = new StringBuilder(2 * bytes.length); 32 for (int i = 0; i < bytes.length; i++) { 33 int b; 34 b = 0x0f & (bytes[i] >> 4); 35 ret.append(HEX_CHARS[b]); 36 b = 0x0f & bytes[i]; 37 ret.append(HEX_CHARS[b]); 38 } 39 return ret.toString(); 40 } 41 42 /** 43 * Converts a hex String to a byte array. 44 * 45 * @param s A string of hexadecimal characters, must be an even number of chars long 46 * @return byte array representation 47 * @throws RuntimeException on invalid format 48 */ hexStringToBytes(String s)49 public static byte[] hexStringToBytes(String s) { 50 byte[] ret; 51 52 if (s == null) return null; 53 54 int sz = s.length(); 55 56 ret = new byte[sz / 2]; 57 58 for (int i = 0; i < sz; i += 2) { 59 ret[i / 2] = (byte) ((hexCharToInt(s.charAt(i)) << 4) | hexCharToInt(s.charAt(i + 1))); 60 } 61 62 return ret; 63 } 64 65 /** 66 * Converts a hex char to its integer value 67 * 68 * @param c A single hexadecimal character. Must be in one of these ranges: 69 * <ul> 70 * <li>'0' to '9' 71 * <li>'a' to 'f' 72 * <li>'A' to 'F' 73 * </ul> 74 * 75 * @return the integer representation of {@code c} 76 * @throws RuntimeException on invalid character 77 */ hexCharToInt(char c)78 public static int hexCharToInt(char c) { 79 if (c >= '0' && c <= '9') return (c - '0'); 80 if (c >= 'A' && c <= 'F') return (c - 'A' + 10); 81 if (c >= 'a' && c <= 'f') return (c - 'a' + 10); 82 83 throw new RuntimeException("invalid hex char '" + c + "'"); 84 } 85 } 86