Java Hex Format formatHexString(final String input, final int charsPerLine)

Here you can find the source of formatHexString(final String input, final int charsPerLine)

Description

format Hex String

License

Open Source License

Declaration

public static String formatHexString(final String input, final int charsPerLine) 

Method Source Code

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

public class Main {
    public final static int BITS_PER_HEX_DIGIT = 4;
    public static final String HEX_STRING_PREFIX1 = "0x";
    public static final String HEX_STRING_PREFIX2 = "0X";

    public static String formatHexString(final String input, final int charsPerLine) {
        StringBuilder buf = new StringBuilder(input.length() * 2);

        int index = 0;
        while ((index + charsPerLine) < input.length()) {
            String str = input.substring(index, index + charsPerLine);
            buf.append(spaceHexString(str));
            buf.append("\n");
            index += charsPerLine;/*  w w w .java2s. c om*/
        }

        String str = input.substring(index);
        buf.append(spaceHexString(str));

        return (buf.toString());
    }

    public static String spaceHexString(String hexString) {
        hexString = stripHexPrefix(hexString);

        int i = 0;
        StringBuilder buf = new StringBuilder(hexString.length() * 2);
        for (i = 0; i < hexString.length(); i += BITS_PER_HEX_DIGIT) {
            if (i + BITS_PER_HEX_DIGIT >= hexString.length()) {
                break;
            }

            buf.append(hexString.substring(i, i + BITS_PER_HEX_DIGIT));
            buf.append(" ");
        }
        buf.append(hexString.substring(i));

        return (buf.toString());
    }

    public static String stripHexPrefix(String hexSymbols) {
        if (hexSymbols.startsWith(HEX_STRING_PREFIX1)) {
            hexSymbols = hexSymbols.substring(HEX_STRING_PREFIX1.length());
        } else if (hexSymbols.startsWith(HEX_STRING_PREFIX2)) {
            hexSymbols = hexSymbols.substring(HEX_STRING_PREFIX2.length());
        }

        return (hexSymbols);
    }
}

Related

  1. formatHex(Integer input)
  2. formatHexBytes(byte[] raw)
  3. formatHexInt(final StringBuilder dst, final int p, int w)
  4. formatHexReversed(String original, int length)
  5. formatHexStr(int width, String hexStr)
  6. formatHexToString(byte[] bytes)
  7. formatInHex(byte[] bySrc, int nLineLen)
  8. formatText(String value, boolean showAsHexFlag)
  9. formatToHex(int rgb)