This function encodes a byte array using base 16 with no indentation of new lines. - Java java.lang

Java examples for java.lang:byte Array Encode Decode

Description

This function encodes a byte array using base 16 with no indentation of new lines.

Demo Code

/************************************************************************
 * Copyright (c) Crater Dog Technologies(TM).  All Rights Reserved.     *
 ************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.        *
 *                                                                      *
 * This code is free software; you can redistribute it and/or modify it *
 * under the terms of The MIT License (MIT), as published by the Open   *
 * Source Initiative. (See http://opensource.org/licenses/MIT)          *
 ************************************************************************/
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(encode(bytes));
    }//www.  j  a  v  a  2  s.  c om

    static private final String lookupTable = "0123456789ABCDEF";

    /**
     * This function encodes a byte array using base 16 with no indentation of new lines.
     *
     * @param bytes The byte array to be encoded.
     * @return The base 16 encoded string.
     */
    static public String encode(byte[] bytes) {
        return encode(bytes, null);
    }

    /**
     * This function encodes a byte array using base 16 with a specific indentation of new lines.
     *
     * @param bytes The byte array to be encoded.
     * @param indentation The indentation string to be inserted before each new line.
     * @return The base 16 encoded string.
     */
    static public String encode(byte[] bytes, String indentation) {
        StringBuilder result = new StringBuilder();
        int length = bytes.length;
        if (length == 0)
            return ""; // empty byte array
        for (int i = 0; i < length; i++) {
            if (indentation != null && length > 40 && i % 40 == 0) {
                // format to indented 80 character blocks
                result.append("\n");
                result.append(indentation);
            }
            int nibble = (bytes[i] & 0xF0) >>> 4;
            result.append(lookupTable.charAt(nibble));
            nibble = bytes[i] & 0x0F;
            result.append(lookupTable.charAt(nibble));
        }
        return result.toString();
    }
}

Related Tutorials