Java Hex Calculate toHexString(final byte b)

Here you can find the source of toHexString(final byte b)

Description

to Hex String

License

Apache License

Declaration

public static String toHexString(final byte b) 

Method Source Code

//package com.java2s;
/*/*from w ww  .  ja va  2  s .  co  m*/
 * Copyright (C) 2006 The Android Open Source Project
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

public class Main {
    private final static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    public static String toHexString(final byte b) {
        return toHexString(toByteArray(b));
    }

    public static String toHexString(final byte[] array) {
        return toHexString(array, 0, array.length);
    }

    public static String toHexString(final byte[] array, final int offset, final int length) {
        final char[] buf = new char[length * 2];

        int bufIndex = 0;
        for (int i = offset; i < (offset + length); i++) {
            final byte b = array[i];
            buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
            buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
        }

        return new String(buf);
    }

    public static String toHexString(final int i) {
        return toHexString(toByteArray(i));
    }

    public static byte[] toByteArray(final byte b) {
        final byte[] array = new byte[1];
        array[0] = b;
        return array;
    }

    public static byte[] toByteArray(final int i) {
        final byte[] array = new byte[4];

        array[3] = (byte) (i & 0xFF);
        array[2] = (byte) ((i >> 8) & 0xFF);
        array[1] = (byte) ((i >> 16) & 0xFF);
        array[0] = (byte) ((i >> 24) & 0xFF);

        return array;
    }
}

Related

  1. toHexString(byte[] val)
  2. toHexString(byte[] value)
  3. toHexString(byte[] value)
  4. toHexString(byte[] value, int startOffset, int maxLength, boolean uppercase, char separator)
  5. toHexString(char c)
  6. toHexString(final byte b)
  7. toHexString(final byte hex)
  8. toHexString(final byte value)
  9. toHexString(final byte[] arr)