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