Java Hex Calculate toHexCharFromBin(final String bin)

Here you can find the source of toHexCharFromBin(final String bin)

Description

to Hex Char From Bin

License

Open Source License

Declaration

public static char toHexCharFromBin(final String bin) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Allowable hex values */
    private final static String[] hexSymbols = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c",
            "d", "e", "f" };
    public final static int BITS_PER_HEX_DIGIT = 4;
    public final static int BINARY_RADIX = 2;
    public static final String BINARY_STRING_PREFIX1 = "0b";
    public static final String BINARY_STRING_PREFIX2 = "0B";

    public static char toHexCharFromBin(final String bin) {
        String bits = stripBinaryPrefix(bin);
        while (bits.length() < BITS_PER_HEX_DIGIT) {
            bits = "0" + bits;
        }//from ww  w.  j av a2  s .c  o  m

        if (bits.length() > BITS_PER_HEX_DIGIT) {
            throw new IllegalArgumentException(
                    "Input bit string \"" + bin + "\" is too long to be a hexadecimal character.");
        }

        int value = Integer.parseInt(bits, BINARY_RADIX);
        return (hexSymbols[value].charAt(0));
    }

    public static String stripBinaryPrefix(String binSymbols) {
        if (binSymbols.startsWith(BINARY_STRING_PREFIX1)) {
            binSymbols = binSymbols.substring(BINARY_STRING_PREFIX1.length());
        } else if (binSymbols.startsWith(BINARY_STRING_PREFIX2)) {
            binSymbols = binSymbols.substring(BINARY_STRING_PREFIX2.length());
        }

        return (binSymbols);
    }
}

Related

  1. toHexChar(int i)
  2. toHexChar(int nibble)
  3. toHexChar(int paramInt)
  4. toHexChar(int value)
  5. toHexCharArray(byte[] input)
  6. toHexChars(byte[] bs)
  7. toHexChars(byte[] bytes)
  8. toHexChars(final int b)
  9. toHexDec(byte[] bytes)