Converting A String To Hexadecimal In Java

前端 未结 21 2265
青春惊慌失措
青春惊慌失措 2020-11-22 09:55

I am trying to convert a string like \"testing123\" into hexadecimal form in java. I am currently using BlueJ.

And to convert it back, is it the same thing except b

相关标签:
21条回答
  • 2020-11-22 10:26

    I would suggest something like this, where str is your input string:

    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());
    }
    
    0 讨论(0)
  • 2020-11-22 10:27

    To go the other way (hex to string), you can use

    public String hexToString(String hex) {
        return new String(new BigInteger(hex, 16).toByteArray());
    }
    
    0 讨论(0)
  • 2020-11-22 10:28
    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 讨论(0)
  • 2020-11-22 10:28

    Here are some benchmarks comparing different approaches and libraries. Guava beats Apache Commons Codec at decoding. Commons Codec beats Guava at encoding. And JHex beats them both for decoding and encoding.

    JHex example

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

    Everything is in a single class file for JHex. Feel free to copy paste if you don't want yet another library in your dependency tree. Also note, it is only available as Java 9 jar until I can figure out how to publish multiple release targets with Gradle and the Bintray plugin.

    0 讨论(0)
  • 2020-11-22 10:32

    To get the Integer value of hex

            //hex like: 0xfff7931e to int
            int hexInt = Long.decode(hexString).intValue();
    
    0 讨论(0)
  • 2020-11-22 10:33

    All answers based on String.getBytes() involve encoding your string according to a Charset. You don't necessarily get the hex value of the 2-byte characters that make up your string. If what you actually want is the equivalent of a hex viewer, then you need to access the chars directly. Here's the function that I use in my code for debugging Unicode issues:

    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();
    }
    

    Then, stringToHex("testing123") will give you:

    0074 0065 0073 0074 0069 006e 0067 0031 0032 0033
    
    0 讨论(0)
提交回复
热议问题