1 /* 2 * Copyright (C) 2024 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.adservices.service.signals; 18 19 /** Utilities for binary encoding */ 20 public class HexEncodingUtil { 21 22 private static final char[] sHexCharacters = { 23 '0', '1', '2', '3', '4', '5', '6', '7', 24 '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 25 }; 26 27 /** Encodes the {@code binary} into a Hex string */ binaryToHex(byte[] binary)28 public static String binaryToHex(byte[] binary) { 29 char[] result = new char[binary.length * 2]; 30 31 int i = 0; 32 for (byte b : binary) { 33 int leftBits = (b & 0b11110000) >> 4; 34 int rightBits = b & 0b00001111; 35 36 result[i++] = sHexCharacters[leftBits]; 37 result[i++] = sHexCharacters[rightBits]; 38 } 39 40 return new String(result); 41 } 42 43 /** Decodes a Hex string into binary. The characters are expected to be in uppercase. */ hexToBinary(String hex)44 public static byte[] hexToBinary(String hex) { 45 byte[] result = new byte[hex.length() / 2]; 46 47 for (int i = 0; i < hex.length(); i += 2) { 48 char leftBitsChar = hex.charAt(i); 49 char rightBitsChar = hex.charAt(i + 1); 50 51 int leftBits = indexOf(leftBitsChar); 52 int rightBits = indexOf(rightBitsChar); 53 54 result[i / 2] = (byte) ((leftBits << 4) | rightBits); 55 } 56 57 return result; 58 } 59 indexOf(char item)60 private static int indexOf(char item) { 61 for (int i = 0; i < sHexCharacters.length; i++) { 62 if (sHexCharacters[i] == item) { 63 return i; 64 } 65 } 66 return -1; 67 } 68 } 69