Home | History | Annotate | Download | only in conscrypt
      1 /*
      2  * Copyright 2013 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 org.conscrypt;
     18 
     19 /**
     20  *
     21  * Helper class for dealing with hexadecimal strings.
     22  *
     23  * @hide
     24  */
     25 @Internal
     26 // public for testing by TrustedCertificateStoreTest
     27 // TODO(nathanmittler): Move to InternalUtil?
     28 public final class Hex {
     29     private Hex() {}
     30 
     31     private final static char[] DIGITS = {
     32             '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
     33 
     34     public static String bytesToHexString(byte[] bytes) {
     35         char[] buf = new char[bytes.length * 2];
     36         int c = 0;
     37         for (byte b : bytes) {
     38             buf[c++] = DIGITS[(b >> 4) & 0xf];
     39             buf[c++] = DIGITS[b & 0xf];
     40         }
     41         return new String(buf);
     42     }
     43 
     44     public static String intToHexString(int i, int minWidth) {
     45         int bufLen = 8;  // Max number of hex digits in an int
     46         char[] buf = new char[bufLen];
     47         int cursor = bufLen;
     48 
     49         do {
     50             buf[--cursor] = DIGITS[i & 0xf];
     51         } while ((i >>>= 4) != 0 || (bufLen - cursor < minWidth));
     52 
     53         return new String(buf, cursor, bufLen - cursor);
     54     }
     55 }
     56