Java Hex Calculate toHexString(byte b)

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

Description

Format a byte into a proper length hex String.

License

Open Source License

Parameter

Parameter Description
b the byte to convert

Return

the byte, converted to a hex string.

Declaration

public static String toHexString(byte b) 

Method Source Code

//package com.java2s;
/*/*  w  w w  .j  a va  2 s  .  com*/
 * Copyright (C) 2014 Jesse Caulfield 
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /**
     * Format a byte into a proper length hex String.
     * <p>
     * This is identical to Long.toHexString() except this pads (with 0's) to the
     * proper size.
     *
     * @param b the byte to convert
     * @return the byte, converted to a hex string.
     */
    public static String toHexString(byte b) {
        return toHexString(unsignedLong(b), '0', 2, 2);
    }

    /**
     * Format a short into a proper length hex String.
     * <p>
     * This is identical to Long.toHexString() except this pads (with 0's) to the
     * proper size.
     *
     * @param s the short to convert
     * @return the short, converted to a hex string.
     */
    public static String toHexString(short s) {
        return toHexString(unsignedLong(s), '0', 4, 4);
    }

    /**
     * Format a int into a proper length hex String.
     * <p>
     * This is identical to Long.toHexString() except this pads (with 0's) to the
     * proper size.
     *
     * @param i the integer to convert
     * @return the integer, converted to a hex string.
     */
    public static String toHexString(int i) {
        return toHexString(unsignedLong(i), '0', 8, 8);
    }

    /**
     * Format a long into the specified length hex String.
     * <p>
     * This is identical to Long.toHexString() except this pads (with 0's) to the
     * proper size.
     *
     * @param l the long to convert
     * @return the long, converted to a hex string.
     */
    public static String toHexString(long l) {
        return toHexString(l, '0', 16, 16);
    }

    /**
     * Format a long into the specified length hex String.
     * <p>
     * This is identical to Long.toHexString() except this pads (with 0's), or
     * truncates, to the specified size. If max &lt; min the functionality is
     * exactly as Long.toHexString().
     *
     * @param l   the long to convert
     * @param c   the character to use for padding
     * @param min the min length of the resulting String
     * @param max the max length of the resulting String
     * @return the long, converted to a hex string.
     */
    public static String toHexString(long l, char c, int min, int max) {
        StringBuilder sb = new StringBuilder(Long.toHexString(l));

        if (max < min) {
            return sb.toString();
        }

        while (sb.length() < max) {
            sb.insert(0, c);
        }

        return sb.substring(sb.length() - min);
    }

    /**
     * Format a byte[] into a hex String.
     * <p>
     * This creates a String by concatenating the result of
     * {@code delimiter + {@link #toHexString(byte) toHexString(byte)}} for each
     * byte in the array. If the specified length is greater than the actual array
     * length, the array length is used. If the specified length (or array length)
     * is 0 or less, the resulting String will be an empty String.
     *
     * @param delimiter The delimiter to prefix every byte with.
     * @param array     The byte[] to convert.
     * @param length    The number of bytes to use.
     * @return A String representing the byte[].
     * @exception NullPointerException If the byte[] is null.
     */
    @SuppressWarnings("AssignmentToMethodParameter")
    public static String toHexString(String delimiter, byte[] array, int length) {
        StringBuilder sb = new StringBuilder();

        if (length > array.length) {
            length = array.length;
        }

        if (length < 0) {
            length = 0;
        }

        for (int i = 0; i < length; i++) {
            sb.append(delimiter).append(toHexString(array[i]));
        }

        return sb.toString();
    }

    /**
     * Format a short[] into a hex String.
     * <p>
     * This creates a String by concatenating the result of
     * {@code delimiter + {@link #toHexString(short) toHexString(short)}} for each
     * short in the array. If the specified length is greater than the actual
     * array length, the array length is used. If the specified length (or array
     * length) is 0 or less, the resulting String will be an empty String.
     *
     * @param delimiter The delimiter to prefix every short with.
     * @param array     The short[] to convert.
     * @param length    The number of shorts to use.
     * @return A String representing the short[].
     * @exception NullPointerException If the short[] is null.
     */
    @SuppressWarnings("AssignmentToMethodParameter")
    public static String toHexString(String delimiter, short[] array, int length) {
        StringBuilder sb = new StringBuilder();

        if (length > array.length) {
            length = array.length;
        }

        if (length < 0) {
            length = 0;
        }

        for (int i = 0; i < length; i++) {
            sb.append(delimiter).append(toHexString(array[i]));
        }

        return sb.toString();
    }

    /**
     * Format a int[] into a hex String.
     * <p>
     * This creates a String by concatenating the result of
     * {@code delimiter + {@link #toHexString(int) toHexString(int)}} for each int
     * in the array. If the specified length is greater than the actual array
     * length, the array length is used. If the specified length (or array length)
     * is 0 or less, the resulting String will be an empty String.
     *
     * @param delimiter The delimiter to prefix every int with.
     * @param array     The int[] to convert.
     * @param length    The number of ints to use.
     * @return A String representing the int[].
     * @exception NullPointerException If the int[] is null.
     */
    @SuppressWarnings("AssignmentToMethodParameter")
    public static String toHexString(String delimiter, int[] array, int length) {
        StringBuilder sb = new StringBuilder();

        if (length > array.length) {
            length = array.length;
        }

        if (length < 0) {
            length = 0;
        }

        for (int i = 0; i < length; i++) {
            sb.append(delimiter).append(toHexString(array[i]));
        }

        return sb.toString();
    }

    /**
     * Format a long[] into a hex String.
     * <p>
     * This creates a String by concatenating the result of
     * {@code delimiter + {@link #toHexString(long) toHexString(long)}} for each
     * long in the array. If the specified length is greater than the actual array
     * length, the array length is used. If the specified length (or array length)
     * is 0 or less, the resulting String will be an empty String.
     *
     * @param delimiter The delimiter to prefix every long with.
     * @param array     The long[] to convert.
     * @param length    The number of longs to use.
     * @return A String representing the long[].
     * @exception NullPointerException If the long[] is null.
     */
    @SuppressWarnings("AssignmentToMethodParameter")
    public static String toHexString(String delimiter, long[] array, int length) {
        StringBuilder sb = new StringBuilder();

        if (length > array.length) {
            length = array.length;
        }

        if (length < 0) {
            length = 0;
        }

        for (int i = 0; i < length; i++) {
            sb.append(delimiter).append(toHexString(array[i]));
        }

        return sb.toString();
    }

    /**
     * Format a byte[] into a hex String.
     * <p>
     * This calls
     * {@link #toHexString(String,byte[],int) toHexString(delimiter, array, array.length)}.
     *
     * @param delimiter The delimiter to prefix every byte with.
     * @param array     The byte[] to convert.
     * @return A String representing the byte[].
     * @exception NullPointerException If the byte[] is null.
     */
    public static String toHexString(String delimiter, byte[] array) {
        return toHexString(delimiter, array, array.length);
    }

    /**
     * Format a short[] into a hex String.
     * <p>
     * This calls
     * {@link #toHexString(String,short[],int) toHexString(delimiter, array, array.length)}.
     *
     * @param delimiter The delimiter to prefix every short with.
     * @param array     The short[] to convert.
     * @return A String representing the short[].
     * @exception NullPointerException If the short[] is null.
     */
    public static String toHexString(String delimiter, short[] array) {
        return toHexString(delimiter, array, array.length);
    }

    /**
     * Format a int[] into a hex String.
     * <p>
     * This calls
     * {@link #toHexString(String,int[],int) toHexString(delimiter, array, array.length)}.
     *
     * @param delimiter The delimiter to prefix every int with.
     * @param array     The int[] to convert.
     * @return A String representing the int[].
     * @exception NullPointerException If the int[] is null.
     */
    public static String toHexString(String delimiter, int[] array) {
        return toHexString(delimiter, array, array.length);
    }

    /**
     * Format a long[] into a hex String.
     * <p>
     * This calls
     * {@link #toHexString(String,long[],int) toHexString(delimiter, array, array.length)}.
     *
     * @param delimiter The delimiter to prefix every long with.
     * @param array     The long[] to convert.
     * @return A String representing the long[].
     * @exception NullPointerException If the long[] is null.
     */
    public static String toHexString(String delimiter, long[] array) {
        return toHexString(delimiter, array, array.length);
    }

    /**
     * Get the specified byte's value as an unsigned long.
     * <p>
     * This converts the specified byte into a long. The least significant byte (8
     * bits) of the long will be identical to the byte (8 bits) provided, and the
     * most significant 7 bytes (56 bits) of the long will be zero.
     * <p>
     * For many of the values in this USB API, unsigned bytes are used. However,
     * since Java does not include unsigned bytes in the language, those unsigned
     * bytes must be converted to a larger storage type before being used in
     * unsigned calculations.
     *
     * @param b the byte to convert.
     * @return An unsigned long representing the specified byte.
     */
    public static long unsignedLong(byte b) {
        return 0x00000000000000ff & b;
    }

    /**
     * Get the specified short's value as an unsigned long.
     * <p>
     * This converts the specified byte into a long. The least significant short
     * (16 bits) of the long will be identical to the short (16 bits) provided,
     * and the most significant 6 bytes (48 bits) of the long will be zero.
     * <p>
     * For many of the values in this USB API, unsigned shorts are used. However,
     * since Java does not include unsigned short in the language, those unsigned
     * shorts must be converted to a larger storage type before being used in
     * unsigned calculations.
     *
     * @param s the short to convert.
     * @return An unsigned long representing the specified short.
     */
    public static long unsignedLong(short s) {
        return 0x000000000000ffff & s;
    }

    /**
     * Get the specified int's value as an unsigned long.
     * <p>
     * This converts the specified int into a long. The least significant int (32
     * bits) of the long will be identical to the int (32 bits) provided, and the
     * most significant int (32 bits) of the long will be zero.
     *
     * @param i the int to convert.
     * @return An unsigned long representing the specified int.
     */
    public static long unsignedLong(int i) {
        return 0x00000000ffffffff & i;
    }

    /**
     * Convert a byte stream to a printable string of bytes, optionally with
     * spaces between each byte value.
     *
     * @param bytes  an array of bytes
     * @param spaces indicator that each byte should be separated by a space
     *               character
     * @return a (potentially very long) non-null String
     */
    public static String toString(byte[] bytes, boolean spaces) {
        StringBuilder sb = new StringBuilder();
        if (bytes != null) {
            for (byte b : bytes) {
                sb.append(Integer.toHexString(b & 0x000000FF)).append(spaces ? " " : "");
            }
        }
        return sb.toString();
    }

    /**
     * Format a byte into a string of 0/1 bits. e..g. "0 1 0 0 0 0 0 0"
     *
     * @param byteCode a byte
     * @param spaces   whether to add spaces between the bits
     * @return a string showing each bit value as one or zero
     */
    public static String toString(byte byteCode, boolean spaces) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            sb.append(getBit(byteCode, i)).append(i == 7 ? "" : spaces ? " " : "");
        }
        return sb.toString();

    }

    /**
     * Format a byte array to a printable String with spaces. This is a shortcut
     * to {@link #toString(byte[], true)}
     *
     * @param bytes an array of bytes
     * @return a (potentially very long) non-null String
     */
    public static String toString(byte[] bytes) {
        return toString(bytes, true);
    }

    /**
     * Print an integer as a Hex String.
     *
     * @param number an integer number
     * @return the number as a Hex String.
     */
    public static String toString(int number) {
        return Integer.toHexString(number);
    }

    /**
     * Get one bit back from a bit string within a multi-byte array at the
     * specified position:
     *
     * @param data the Byte to study
     * @param pos  the bit position to get [0-7] (zero to seven)
     * @return returns zero or one
     */
    public static int getBit(byte[] data, int pos) {
        int posByte = pos / 8;
        int posBit = pos % 8;
        byte valByte = data[posByte];
        int valInt = valByte >> (8 - (posBit + 1)) & 0x0001;
        return valInt;
    }

    /**
     * Get one bit back from a bit string within a single byte at the specified
     * position:
     *
     * @param data the Byte to study
     * @param pos  the bit position to get [0-7] (zero to seven)
     * @return returns zero or one
     */
    public static int getBit(byte data, int pos) {
        //    int posByte = pos / 8;
        int posBit = pos % 8;
        //    byte valByte = data;
        int valInt = data >> (8 - (posBit + 1)) & 0x0001;
        return valInt;
    }
}

Related

  1. toHexStream(byte[] bytes, String delimiter, boolean prefixEachValue, boolean upperCase)
  2. toHexString(byte a)
  3. toHexString(byte abyte0[], boolean spaceFlag)
  4. toHexString(byte b)
  5. toHexString(byte b)
  6. toHexString(byte b)
  7. toHexString(byte b)
  8. toHexString(byte b)
  9. toHexString(byte b)