Java Hex Calculate toHexString(byte[] data)

Here you can find the source of toHexString(byte[] data)

Description

to Hex String

License

Open Source License

Declaration

public static String toHexString(byte[] data) 

Method Source Code

//package com.java2s;
/*/*from  w w w  .  j av  a 2  s.c  o m*/
 * This file is part of M.O.R.F.
 *                      <https://github.com/HeXLaB/M.O.R.F.>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 * Copyright (c) 2013-2014
 *               HeXLaB Team
 *                           All rights reserved
 */

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

    public static String toHexString(byte[] data, int offset, int len) {
        final StringBuilder result = new StringBuilder();

        for (int i = offset; i < len; i++) {
            result.append(fillHex(data[i] & 0xff, 2));
        }

        return result.toString();
    }

    /**
     * Converts a number to hexadecimal format and adds leading zeros if necessary.
     *
     * @param data
     *     a number
     * @param digits
     *     minimum hexadecimal digit count
     *
     * @return given number in hexadecimal format
     */
    public static String fillHex(int data, int digits) {
        String hex = Integer.toHexString(data);

        StringBuilder number = new StringBuilder(Math.max(hex.length(), digits));
        for (int i = hex.length(); i < digits; i++) {
            number.append(0);
        }
        number.append(hex);

        return number.toString();
    }
}

Related

  1. toHexString(byte[] bytes, String separator, boolean upperCase)
  2. toHexString(byte[] coded)
  3. toHexString(byte[] color)
  4. toHexString(byte[] content, int len)
  5. toHexString(byte[] data)
  6. toHexString(byte[] data)
  7. toHexString(byte[] data)
  8. toHexString(byte[] data)
  9. toHexString(byte[] data)