1 /* 2 * Copyright (C) 2022 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 com.android.server.nearby.util; 18 19 /** 20 * Hex class that contains hex related functions. 21 */ 22 public class Hex { 23 24 private static final char[] HEX_UPPERCASE = { 25 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 26 }; 27 28 private static final char[] HEX_LOWERCASE = { 29 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 30 }; 31 32 /** 33 * Bytes array to lower case string. 34 */ bytesToStringLowercase(byte[] bytes)35 public static String bytesToStringLowercase(byte[] bytes) { 36 char[] hexChars = new char[bytes.length * 2]; 37 int j = 0; 38 for (byte aByte : bytes) { 39 int v = aByte & 0xFF; 40 hexChars[j++] = HEX_LOWERCASE[v >>> 4]; 41 hexChars[j++] = HEX_LOWERCASE[v & 0x0F]; 42 } 43 return new String(hexChars); 44 } 45 46 /** 47 * Encodes the byte array to string. 48 */ bytesToStringUppercase(byte[] bytes)49 public static String bytesToStringUppercase(byte[] bytes) { 50 return bytesToStringUppercase(bytes, false /* zeroTerminated */); 51 } 52 53 /** Encodes a byte array as a hexadecimal representation of bytes. */ bytesToStringUppercase(byte[] bytes, boolean zeroTerminated)54 public static String bytesToStringUppercase(byte[] bytes, boolean zeroTerminated) { 55 int length = bytes.length; 56 StringBuilder out = new StringBuilder(length * 2); 57 for (int i = 0; i < length; i++) { 58 if (zeroTerminated && i == length - 1 && (bytes[i] & 0xff) == 0) { 59 break; 60 } 61 out.append(HEX_UPPERCASE[(bytes[i] & 0xf0) >>> 4]); 62 out.append(HEX_UPPERCASE[bytes[i] & 0x0f]); 63 } 64 return out.toString(); 65 } 66 /** 67 * Converts string to byte array. 68 */ stringToBytes(String hex)69 public static byte[] stringToBytes(String hex) throws IllegalArgumentException { 70 int length = hex.length(); 71 if (length % 2 != 0) { 72 throw new IllegalArgumentException("Hex string has odd number of characters"); 73 } 74 byte[] out = new byte[length / 2]; 75 for (int i = 0; i < length; i += 2) { 76 // Byte.parseByte() doesn't work here because it expects a hex value in -128, 127, and 77 // our hex values are in 0, 255. 78 out[i / 2] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16); 79 } 80 return out; 81 } 82 } 83