Рубрики
Без рубрики

Как преобразовать строку в шестнадцатеричную в Java

– Как преобразовать строку в шестнадцатеричную в Java

Вот несколько примеров преобразования Java между строкой или ASCII в и из//Шестнадцатеричный .

  • Кодек Apache Commons – Шестнадцатеричный
  • Целое число
  • Побитовый
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

1. Кодек Apache Commons

Оба Шестнадцатеричный код. и Hex.decodehex может преобразовывать строку в шестнадцатеричную и наоборот.

  
      commons-codec
      commons-codec
      1.14
  
package com.mkyong;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.nio.charset.StandardCharsets;

public class HexUtils {

    public static void main(String[] args) {

        String input = "a";
        System.out.println("input : " + input);

        String hex = convertStringToHex(input);
        System.out.println("hex : " + hex);

        String result = convertHexToString(hex);
        System.out.println("result : " + result);

    }

    public static String convertStringToHex(String str) {

        // display in uppercase
        //char[] chars = Hex.encodeHex(str.getBytes(StandardCharsets.UTF_8), false);

        // display in lowercase, default
        char[] chars = Hex.encodeHex(str.getBytes(StandardCharsets.UTF_8));

        return String.valueOf(chars);
    }

    public static String convertHexToString(String hex) {

        String result = "";
        try {
            byte[] bytes = Hex.decodeHex(hex);
            result = new String(bytes, StandardCharsets.UTF_8);
        } catch (DecoderException e) {
            throw new IllegalArgumentException("Invalid Hex format!");
        }
        return result;
    }
}

Выход

input : a
hex : 61
result : a

2. Целое число

Этот пример прост для понимания, используйте JDK Целое число API, такие как Целое число.toHexString и Integer.parseInt(шестнадцатеричный, 16) для преобразования строки в шестнадцатеричный и наоборот.

Идея в том, чтобы преобразовать Строка <==> Десятичное число <==> Шестнадцатеричный , например, символ a , десятичный – 97, шестнадцатеричный – 61.

package com.mkyong;

public class HexUtils2 {

    public static void main(String[] args) {

        String input = "a";
        System.out.println("input : " + input);

        String hex = convertStringToHex(input);
        System.out.println("hex : " + hex);

        String result = convertHexToString(hex);
        System.out.println("result : " + result);

    }

    // Char -> Decimal -> Hex
    public static String convertStringToHex(String str) {

        StringBuffer hex = new StringBuffer();

        // loop chars one by one
        for (char temp : str.toCharArray()) {

            // convert char to int, for char `a` decimal 97
            int decimal = (int) temp;

            // convert int to hex, for decimal 97 hex 61
            hex.append(Integer.toHexString(decimal));
        }

        return hex.toString();

    }

    // Hex -> Decimal -> Char
    public static String convertHexToString(String hex) {

        StringBuilder result = new StringBuilder();

        // split into two chars per loop, hex, 0A, 0B, 0C...
        for (int i = 0; i < hex.length() - 1; i += 2) {

            String tempInHex = hex.substring(i, (i + 2));

            //convert hex to decimal
            int decimal = Integer.parseInt(tempInHex, 16);

            // convert the decimal to char
            result.append((char) decimal);

        }

        return result.toString();

    }

}

Выход

input : a
hex : 61
result : a

Для ввода Ява

input : java
hex : 6a617661
result : java

3. Побитовый

Это побитовое преобразование аналогично исходному коду кодека Apache Commons, прочитайте комментарий для пояснения.

package com.mkyong;

import java.nio.charset.StandardCharsets;

public class HexUtils3 {

    private static final char[] HEX_UPPER = "0123456789ABCDEF".toCharArray();
    private static final char[] HEX_LOWER = "0123456789abcdef".toCharArray();

    public static void main(String[] args) {

        String input = "java";
        System.out.println("input : " + input);

        String hex = convertStringToHex(input, false);
        System.out.println("hex : " + hex);

    }

    public static String convertStringToHex(String str, boolean lowercase) {

        char[] HEX_ARRAY = lowercase ? HEX_LOWER : HEX_UPPER;

        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);

        // two chars form the hex value.
        char[] hex = new char[bytes.length * 2];

        for (int j = 0; j < bytes.length; j++) {

            // 1 byte = 8 bits,
            // upper 4 bits is the first half of hex
            // lower 4 bits is the second half of hex
            // combine both and we will get the hex value, 0A, 0B, 0C

            int v = bytes[j] & 0xFF;               // byte widened to int, need mask 0xff
                                                   // prevent sign extension for negative number

            hex[j * 2] = HEX_ARRAY[v >>> 4];       // get upper 4 bits

            hex[j * 2 + 1] = HEX_ARRAY[v & 0x0F];  // get lower 4 bits

        }

        return new String(hex);

    }

}

Выход

input : java
hex : 6A617661

Примечание Если вы в замешательстве, выберите кодек Apache Commons для безопасной ставки.

Рекомендации

Оригинал: “https://mkyong.com/java/how-to-convert-hex-to-ascii-in-java/”