Conversion D'Une Chaîne En Hexadécimal En Java


J'essaie de convertir une chaîne comme "testing123" en forme hexadécimale en java. J'utilise actuellement BlueJ.

Et pour le convertir en arrière, est-ce la même chose sauf en arrière?

Author: Joni, 2009-05-29

21 answers

Voici un court moyen de le convertir en hexadécimal:

public String toHex(String arg) {
    return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
 204
Author: Kaleb Pederson, 2013-09-22 13:32:57

Pour s'assurer que l'hexadécimal est toujours de 40 caractères, le BigInteger doit être positif:

public String toHex(String arg) {
  return String.format("%x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
 63
Author: Jos Theeuwen, 2010-10-15 09:06:38
import org.apache.commons.codec.binary.Hex;
...

String hexString = Hex.encodeHexString(myString.getBytes(/* charset */));

Http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Hex.html

 45
Author: Joshua Swink, 2012-01-24 19:57:08

Les nombres que vous encodez en hexadécimal doivent représenter un codage des caractères, tel que UTF-8. Donc, convertissez d'abord la chaîne en un octet[] représentant la chaîne dans cet encodage, puis convertissez chaque octet en hexadécimal.

public static String hexadecimal(String input, String charsetName) throws UnsupportedEncodingException {
    if (input == null) throw new NullPointerException();
    return asHex(input.getBytes(charsetName));
}

private static final char[] HEX_CHARS = "0123456789abcdef".toCharArray();

public static String asHex(byte[] buf)
{
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i)
    {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}
 20
Author: Stephen Denne, 2009-05-29 00:34:55

Utiliser DatatypeConverter.printHexBinary():

public static String toHexadecimal(String text) throws UnsupportedEncodingException
{
    byte[] myBytes = text.getBytes("UTF-8");

    return DatatypeConverter.printHexBinary(myBytes);
}

Exemple d'utilisation:

System.out.println(toHexadecimal("Hello StackOverflow"));

Imprime:

48656C6C6F20537461636B4F766572666C6F77

Remarque : Cela provoque un petit problème supplémentaire avec Java 9 et plus récent car l'API n'est pas incluse par défaut. Pour référence, par exemple, voir this GitHub problème.

 17
Author: BullyWiiPlaza, 2019-05-12 10:33:18

Voici une autre solution

public static String toHexString(byte[] ba) {
    StringBuilder str = new StringBuilder();
    for(int i = 0; i < ba.length; i++)
        str.append(String.format("%x", ba[i]));
    return str.toString();
}

public static String fromHexString(String hex) {
    StringBuilder str = new StringBuilder();
    for (int i = 0; i < hex.length(); i+=2) {
        str.append((char) Integer.parseInt(hex.substring(i, i + 2), 16));
    }
    return str.toString();
}
 11
Author: jordeu, 2012-04-11 07:37:22

Toutes les réponses basées sur une chaîne.getBytes () implique l'encodage de votre chaîne en fonction d'un jeu de caractères. Vous n'obtenez pas nécessairement la valeur hexadécimale des caractères de 2 octets qui composent votre chaîne. Si ce que vous voulez réellement est l'équivalent d'une visionneuse hexadécimale, vous devez accéder directement aux caractères. Voici la fonction que j'utilise dans mon code pour déboguer les problèmes Unicode:

static String stringToHex(String string) {
  StringBuilder buf = new StringBuilder(200);
  for (char ch: string.toCharArray()) {
    if (buf.length() > 0)
      buf.append(' ');
    buf.append(String.format("%04x", (int) ch));
  }
  return buf.toString();
}

Ensuite, stringToHex ("testing123") vous donnera:

0074 0065 0073 0074 0069 006e 0067 0031 0032 0033
 6
Author: Bogdan Calmac, 2013-08-15 20:34:05

Pour obtenir la valeur entière de hex

        //hex like: 0xfff7931e to int
        int hexInt = Long.decode(hexString).intValue();
 5
Author: TouchBoarder, 2012-06-11 12:56:43
byte[] bytes = string.getBytes(CHARSET); // you didn't say what charset you wanted
BigInteger bigInt = new BigInteger(bytes);
String hexString = bigInt.toString(16); // 16 is the radix

Vous pouvez retourner hexString à ce stade, avec la mise en garde que les caractères nuls principaux seront supprimés, et le résultat aura une longueur impaire si le premier octet est inférieur à 16. Si vous avez besoin de gérer ces cas, vous pouvez ajouter du code supplémentaire au pad avec 0s:

StringBuilder sb = new StringBuilder();
while ((sb.length() + hexString.length()) < (2 * bytes.length)) {
  sb.append("0");
}
sb.append(hexString);
return sb.toString();
 4
Author: Laurence Gonsalves, 2009-05-29 00:50:01

Convertir une lettre en code hexadécimal et un code hexadécimal en lettre.

        String letter = "a";
    String code;
    int decimal;

    code = Integer.toHexString(letter.charAt(0));
    decimal = Integer.parseInt(code, 16);

    System.out.println("Hex code to " + letter + " = " + code);
    System.out.println("Char to " + code + " = " + (char) decimal);
 4
Author: Marcus Becker, 2013-11-19 12:52:20

Je suggérerais quelque chose comme ça, où str est votre chaîne d'entrée:

StringBuffer hex = new StringBuffer();
char[] raw = tokens[0].toCharArray();
for (int i=0;i<raw.length;i++) {
    if     (raw[i]<=0x000F) { hex.append("000"); }
    else if(raw[i]<=0x00FF) { hex.append("00" ); }
    else if(raw[i]<=0x0FFF) { hex.append("0"  ); }
    hex.append(Integer.toHexString(raw[i]).toUpperCase());
}
 4
Author: rodion, 2014-12-31 15:55:52

Pour aller dans l'autre sens (hexadécimal en chaîne), vous pouvez utiliser

public String hexToString(String hex) {
    return new String(new BigInteger(hex, 16).toByteArray());
}
 3
Author: Jibby, 2015-07-05 23:56:24

Convertissez-le d'abord en octets à l'aide de la fonction getBytes (), puis convertissez - le en hexadécimal:

private static String hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<bytes.length; i++) {
        sb.append(String.format("%02X ",bytes[i]));
    }
    return sb.toString();
}
 2
Author: user2475511, 2015-04-02 10:05:59

Utilisation de l'aide de plusieurs personnes à partir de plusieurs Threads..

Je sais que cela a été répondu, mais je voudrais donner une méthode d'encodage et de décodage complète pour tous les autres dans ma même situation..

Voici mes méthodes d'encodage et de décodage..

// Global Charset Encoding
public static Charset encodingType = StandardCharsets.UTF_8;

// Text To Hex
public static String textToHex(String text)
{
    byte[] buf = null;
    buf = text.getBytes(encodingType);
    char[] HEX_CHARS = "0123456789abcdef".toCharArray();
    char[] chars = new char[2 * buf.length];
    for (int i = 0; i < buf.length; ++i)
    {
        chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
        chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
    }
    return new String(chars);
}

// Hex To Text
public static String hexToText(String hex)
{
    int l = hex.length();
    byte[] data = new byte[l / 2];
    for (int i = 0; i < l; i += 2)
    {
        data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
            + Character.digit(hex.charAt(i + 1), 16));
    }
    String st = new String(data, encodingType);
    return st;
}
 2
Author: Gadget Guru, 2019-09-10 08:53:08

Convertit une Chaîne en Hexadécimal:

public String hexToString(String hex) {
    return Integer.toHexString(Integer.parseInt(hex));
}

C'est certainement le moyen le plus simple.

 1
Author: Jorgesys, 2017-01-04 15:43:31

Beaucoup mieux:

public static String fromHexString(String hex, String sourceEncoding ) throws  IOException{
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    byte[] buffer = new byte[512];
    int _start=0;
    for (int i = 0; i < hex.length(); i+=2) {
        buffer[_start++] = (byte)Integer.parseInt(hex.substring(i, i + 2), 16);
        if (_start >=buffer.length || i+2>=hex.length()) {
            bout.write(buffer);
            Arrays.fill(buffer, 0, buffer.length, (byte)0);
            _start  = 0;
        }
    }

    return  new String(bout.toByteArray(), sourceEncoding);
}
 0
Author: Dmitriy Bocharov, 2012-06-05 12:50:21
import java.io.*;
import java.util.*;

public class Exer5{

    public String ConvertToHexadecimal(int num){
        int r;
        String bin="\0";

        do{
            r=num%16;
            num=num/16;

            if(r==10)
            bin="A"+bin;

            else if(r==11)
            bin="B"+bin;

            else if(r==12)
            bin="C"+bin;

            else if(r==13)
            bin="D"+bin;

            else if(r==14)
            bin="E"+bin;

            else if(r==15)
            bin="F"+bin;

            else
            bin=r+bin;
        }while(num!=0);

        return bin;
    }

    public int ConvertFromHexadecimalToDecimal(String num){
        int a;
        int ctr=0;
        double prod=0;

        for(int i=num.length(); i>0; i--){

            if(num.charAt(i-1)=='a'||num.charAt(i-1)=='A')
            a=10;

            else if(num.charAt(i-1)=='b'||num.charAt(i-1)=='B')
            a=11;

            else if(num.charAt(i-1)=='c'||num.charAt(i-1)=='C')
            a=12;

            else if(num.charAt(i-1)=='d'||num.charAt(i-1)=='D')
            a=13;

            else if(num.charAt(i-1)=='e'||num.charAt(i-1)=='E')
            a=14;

            else if(num.charAt(i-1)=='f'||num.charAt(i-1)=='F')
            a=15;

            else
            a=Character.getNumericValue(num.charAt(i-1));
            prod=prod+(a*Math.pow(16, ctr));
            ctr++;
        }
        return (int)prod;
    }

    public static void main(String[] args){

        Exer5 dh=new Exer5();
        Scanner s=new Scanner(System.in);

        int num;
        String numS;
        int choice;

        System.out.println("Enter your desired choice:");
        System.out.println("1 - DECIMAL TO HEXADECIMAL             ");
        System.out.println("2 - HEXADECIMAL TO DECIMAL              ");
        System.out.println("0 - EXIT                          ");

        do{
            System.out.print("\nEnter Choice: ");
            choice=s.nextInt();

            if(choice==1){
                System.out.println("Enter decimal number: ");
                num=s.nextInt();
                System.out.println(dh.ConvertToHexadecimal(num));
            }

            else if(choice==2){
                System.out.println("Enter hexadecimal number: ");
                numS=s.next();
                System.out.println(dh.ConvertFromHexadecimalToDecimal(numS));
            }
        }while(choice!=0);
    }
}
 0
Author: Rowena Jimenez, 2012-08-01 08:33:52
new BigInteger(1, myString.getBytes(/*YOUR_CHARSET?*/)).toString(16)
 0
Author: ultraon, 2015-09-16 09:26:49

Voici quelques benchmarks comparant différentes approches et bibliothèques. Goyave bat le codec Apache Commons au décodage. Commons Codec bat Goyava à l'encodage. Et JHex les bat à la fois pour le décodage et l'encodage.

Exemple JHex

String hexString = "596f752772652077656c636f6d652e";
byte[] decoded = JHex.decodeChecked(hexString);
System.out.println(new String(decoded));
String reEncoded = JHex.encode(decoded);

Tout est dans un fichier de classe unique pour JHex. N'hésitez pas à copier coller si vous ne voulez pas encore une autre bibliothèque dans votre arbre de dépendances. Notez également qu'il n'est disponible que sous Java 9 jar jusqu'à ce que je puisse comprendre comment publier plusieurs cibles de publication avec Gradle et le plugin Bintray.

 0
Author: jamespedwards42, 2020-06-20 09:12:55

Vérifiez cette solution pour String to hex et hex to String étau-versa

public class TestHexConversion {
public static void main(String[] args) {
    try{
        String clearText = "testString For;0181;with.love";
        System.out.println("Clear Text  = " + clearText);
        char[] chars = clearText.toCharArray();
        StringBuffer hex = new StringBuffer();
        for (int i = 0; i < chars.length; i++) {
            hex.append(Integer.toHexString((int) chars[i]));
        }
        String hexText = hex.toString();
        System.out.println("Hex Text  = " + hexText);
        String decodedText = HexToString(hexText);
        System.out.println("Decoded Text = "+decodedText);
    } catch (Exception e){
        e.printStackTrace();
    }
}

public static String HexToString(String hex){

      StringBuilder finalString = new StringBuilder();
      StringBuilder tempString = new StringBuilder();

      for( int i=0; i<hex.length()-1; i+=2 ){
          String output = hex.substring(i, (i + 2));
          int decimal = Integer.parseInt(output, 16);
          finalString.append((char)decimal);
          tempString.append(decimal);
      }
    return finalString.toString();
}

Sortie comme suit :

Texte clair = testString Pour;0181;avec.amour

Texte hexadécimal = 74657374537472696e6720466f723b303138313b776974682e6c6f7665

Texte Décodé = chaîne de test Pour;0181;avec.amour

 0
Author: Nitin Upadhyay, 2020-06-20 09:12:55

Un moyen court et pratique de convertir une chaîne en sa notation hexadécimale est:

public static void main(String... args){
String str = "Hello! This is test string.";
char ch[] = str.toCharArray();
StringBuilder sb = new StringBuilder();
    for (int i = 0; i < ch.length; i++) {
        sb.append(Integer.toHexString((int) ch[i]));
    }
    System.out.println(sb.toString());
}
 -1
Author: Amit Samuel, 2018-07-31 08:02:58