Java Hex Calculate toHexString(String data)

Here you can find the source of toHexString(String data)

Description

Convert string to hex string.

License

Open Source License

Parameter

Parameter Description
data a String object.

Return

hex string.

Declaration

public static String toHexString(String data) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *
 * Copyright (c) 2002, 2008 IBM Corporation, Beacon Information Technology Inc. and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from w  w w  .  j  a va  2s  .c om
 *   IBM      - Initial API and implementation
 *   BeaconIT - Initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Convert string to hex string.
     * @param data  a String object.
     * @return hex string.
     */
    public static String toHexString(String data) {
        char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        // Get string as byte array
        byte[] byteData = data.getBytes();

        // Get length
        int length = byteData.length;

        // Create Char buffer
        char[] charBuffer = new char[length * 2];

        int next;
        for (int byteCnt = 0, charCnt = 0; byteCnt < length;) {
            next = byteData[byteCnt++];
            charBuffer[charCnt++] = HEX_CHARS[(next >>> 4) & 0x0F];
            charBuffer[charCnt++] = HEX_CHARS[next & 0x0F];
        }

        return new String(charBuffer);
    }

    /**
     * Convert byte buffer to hex string.
     * @param data  a byte array.
     * @return hex string.
     */
    public static String toHexString(byte[] byteData) {
        char[] HEX_CHARS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

        // Get length
        int length = byteData.length;

        // Create Char buffer
        char[] charBuffer = new char[length * 2];

        int next;
        for (int byteCnt = 0, charCnt = 0; byteCnt < length;) {
            next = byteData[byteCnt++];
            charBuffer[charCnt++] = HEX_CHARS[(next >>> 4) & 0x0F];
            charBuffer[charCnt++] = HEX_CHARS[next & 0x0F];
        }

        return new String(charBuffer);
    }
}

Related

  1. toHexString(long l)
  2. toHexString(long l)
  3. toHexString(long value, int digits)
  4. toHexString(long value, int digits)
  5. ToHexString(long[] data)
  6. toHexString(String input)
  7. toHexString(String s)
  8. toHexString(String s)
  9. toHexString(String s)