Java Hex to Byte convertHexDigit(byte b)

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

Description

convert Hex Digit

License

Open Source License

Parameter

Parameter Description
b An ASCII encoded character 0-9 a-f A-F

Return

The byte value of the character 0-16.

Declaration

public static byte convertHexDigit(byte b) 

Method Source Code

//package com.java2s;
//are made available under the terms of the Eclipse Public License v1.0

public class Main {
    /**/*from  w  ww . j  a va 2s.c o  m*/
     * @param b An ASCII encoded character 0-9 a-f A-F
     * @return The byte value of the character 0-16.
     */
    public static byte convertHexDigit(byte b) {
        if ((b >= '0') && (b <= '9'))
            return (byte) (b - '0');
        if ((b >= 'a') && (b <= 'f'))
            return (byte) (b - 'a' + 10);
        if ((b >= 'A') && (b <= 'F'))
            return (byte) (b - 'A' + 10);
        throw new IllegalArgumentException("!hex:" + Integer.toHexString(0xff & b));
    }

    public static String toHexString(byte b) {
        return toHexString(new byte[] { b }, 0, 1);
    }

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

    public static String toHexString(byte[] b, int offset, int length) {
        StringBuilder buf = new StringBuilder();
        for (int i = offset; i < offset + length; i++) {
            int bi = 0xff & b[i];
            int c = '0' + (bi / 16) % 16;
            if (c > '9')
                c = 'A' + (c - '0' - 10);
            buf.append((char) c);
            c = '0' + bi % 16;
            if (c > '9')
                c = 'a' + (c - '0' - 10);
            buf.append((char) c);
        }
        return buf.toString();
    }

    public static String toString(byte[] bytes, int base) {
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            int bi = 0xff & b;
            int c = '0' + (bi / base) % base;
            if (c > '9')
                c = 'a' + (c - '0' - 10);
            buf.append((char) c);
            c = '0' + bi % base;
            if (c > '9')
                c = 'a' + (c - '0' - 10);
            buf.append((char) c);
        }
        return buf.toString();
    }
}

Related

  1. convertHexCharacterToHalfByte(char character)
  2. convertHexDigit(byte b)
  3. convertHexDigit(byte b)
  4. convertHexDigit(byte b)
  5. convertHexDigit(byte c)