Here you can find the source of toHexFromBin(final String binSymbols)
Parameter | Description |
---|---|
binSymbols | The binary symbol string to transform |
public static String toHexFromBin(final String binSymbols)
//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"; /**/*from w w w. j a v a 2 s. c o m*/ * Transform a string of binary symbols to a string of hex symbols * * @param binSymbols * The binary symbol string to transform * @return The hex string corresponding to the input binary string */ public static String toHexFromBin(final String binSymbols) { String bits = stripBinaryPrefix(binSymbols); while ((bits.length() % BITS_PER_HEX_DIGIT) != 0) { bits = "0" + bits; } StringBuilder hex = new StringBuilder(bits.length() / BITS_PER_HEX_DIGIT); for (int i = 0; i < bits.length(); i += BITS_PER_HEX_DIGIT) { String bitsToAdd = null; if ((i + BITS_PER_HEX_DIGIT) < bits.length()) { bitsToAdd = bits.substring(i, i + BITS_PER_HEX_DIGIT); } else { bitsToAdd = bits.substring(i); } hex.append(toHexCharFromBin(bitsToAdd)); } return (hex.toString()); } 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); } public static char toHexCharFromBin(final String bin) { String bits = stripBinaryPrefix(bin); while (bits.length() < BITS_PER_HEX_DIGIT) { bits = "0" + bits; } 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)); } }