Java String to Hex convertStringToHexString(String data)

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

Description

Convert the string to hex string value.

License

Apache License

Parameter

Parameter Description
data is case sensitive.

Return

the hex string representation of string.

Declaration

public static String convertStringToHexString(String data) 

Method Source Code

//package com.java2s;
/*/*  w  w  w .ja v  a  2 s  . com*/
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

public class Main {
    private static final char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f' };

    /**
     * Convert the string to hex string value.
     * 
     * @param data is case sensitive.
     * @return the hex string representation of string.
     */
    public static String convertStringToHexString(String data) {
        return conventBytesToHexString(data.getBytes());
    }

    /**
     * Convert bytes to hex string.
     * 
     * @param data is the bytes.
     * @return the hex string representation of bytes.
     */
    public static String conventBytesToHexString(byte[] data) {
        return convertBytesToHexString(data, 0, data.length);
    }

    /**
     * Convert bytes to hex string value (using Big-Endian rule).
     * 
     * @param data is the bytes.
     * @param offset is the offset.
     * @param length is the length.
     * @return the hex string representation of bytes.
     */
    public static String convertBytesToHexString(byte[] data, int offset, int length) {
        return convertBytesToHexString(data, offset, length, "");
    }

    public static String convertBytesToHexString(byte[] data, int offset, int length, String byteDelimiter) {
        final StringBuilder stringBuilder = new StringBuilder((length - offset) * (2 + byteDelimiter.length()));
        for (int i = offset; i < length; i++) {
            stringBuilder.append(hexChar[(data[i] >> 4) & 0x0f]);
            stringBuilder.append(hexChar[data[i] & 0x0f]);
            stringBuilder.append(byteDelimiter);
        }
        return stringBuilder.toString();
    }
}

Related

  1. convertStringToHex(String str)
  2. convertStringToHexComma(String plain, boolean appendNullSigns)
  3. convertStringtoHexFormat(String stringToConvert)