• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2021 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.libraries.entitlement.utils;
18 
19 import androidx.annotation.Nullable;
20 
21 import java.nio.ByteBuffer;
22 
23 public class BytesConverter {
24     private static final int INTEGER_SIZE = 4; // 4 bytes
25 
26     // A table mapping from a number to a hex character for fast encoding hex strings.
27     private static final char[] HEX_CHARS = {
28             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
29     };
30 
31     /**
32      * Converts a byte array into a String of hexadecimal characters.
33      *
34      * @param bytes an array of bytes
35      * @return hex string representation of bytes array
36      */
37     @Nullable
convertBytesToHexString(byte[] bytes)38     public static String convertBytesToHexString(byte[] bytes) {
39         if (bytes == null) {
40             return null;
41         }
42 
43         StringBuilder ret = new StringBuilder(2 * bytes.length);
44 
45         for (int i = 0; i < bytes.length; i++) {
46             int b;
47             b = 0x0f & (bytes[i] >> 4);
48             ret.append(HEX_CHARS[b]);
49             b = 0x0f & bytes[i];
50             ret.append(HEX_CHARS[b]);
51         }
52 
53         return ret.toString();
54     }
55 
56     /**
57      * Converts integer to 4 bytes.
58      */
convertIntegerTo4Bytes(int value)59     public static byte[] convertIntegerTo4Bytes(int value) {
60         return ByteBuffer.allocate(INTEGER_SIZE).putInt(value).array();
61     }
62 }
63