1 /* 2 * Copyright (C) 2017 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.util; 18 19 /** 20 * A utility class for common byte array to hex string operations and vise versa. 21 * 22 * @hide 23 */ 24 public final class ByteStringUtils { 25 private static final char[] HEX_LOWERCASE_ARRAY = "0123456789abcdef".toCharArray(); 26 private static final char[] HEX_UPPERCASE_ARRAY = "0123456789ABCDEF".toCharArray(); 27 ByteStringUtils()28 private ByteStringUtils() { 29 /* hide constructor */ 30 } 31 32 /** 33 * Returns the hex encoded string representation of bytes. 34 * @param bytes Byte array to encode. 35 * @return Hex encoded string representation of bytes. 36 */ toHexString(byte[] bytes)37 public static String toHexString(byte[] bytes) { 38 if (bytes == null || bytes.length == 0 || bytes.length % 2 != 0) { 39 return null; 40 } 41 42 final int byteLength = bytes.length; 43 final int charCount = 2 * byteLength; 44 final char[] chars = new char[charCount]; 45 46 for (int i = 0; i < byteLength; i++) { 47 final int byteHex = bytes[i] & 0xFF; 48 chars[i * 2] = HEX_UPPERCASE_ARRAY[byteHex >>> 4]; 49 chars[i * 2 + 1] = HEX_UPPERCASE_ARRAY[byteHex & 0x0F]; 50 } 51 return new String(chars); 52 } 53 54 /** 55 * Returns the decoded byte array representation of str. 56 * @param str Hex encoded string to decode. 57 * @return Decoded byte array representation of str. 58 */ fromHexToByteArray(String str)59 public static byte[] fromHexToByteArray(String str) { 60 if (str == null || str.length() == 0 || str.length() % 2 != 0) { 61 return null; 62 } 63 64 final char[] chars = str.toCharArray(); 65 final int charLength = chars.length; 66 final byte[] bytes = new byte[charLength / 2]; 67 68 for (int i = 0; i < bytes.length; i++) { 69 bytes[i] = 70 (byte) (((getIndex(chars[i * 2]) << 4) & 0xF0) 71 | (getIndex(chars[i * 2 + 1]) & 0x0F)); 72 } 73 return bytes; 74 } 75 getIndex(char c)76 private static int getIndex(char c) { 77 for (int i = 0; i < HEX_UPPERCASE_ARRAY.length; i++) { 78 if (HEX_UPPERCASE_ARRAY[i] == c || HEX_LOWERCASE_ARRAY[i] == c) { 79 return i; 80 } 81 } 82 return -1; 83 } 84 } 85