简体   繁体   中英

Java String to hex string

I'm trying to create a genetic algorithm and I've got this code:

public Cromosoma() {
    this.setRepresentacionBinaria(this.generarAleatoriamenteCromosoma());
}

private String generarAleatoriamenteCromosoma() {
    String cromosoma = "";
    for (int i = 1; i <= 40; i++) {
        cromosoma += ((int) (Math.random() * 10)) % 2;
    }
    return cromosoma;
}

public String getRepresentacionBinaria() {
    return this.representacionBinaria;
}

public String getRepresentacionHexadecimal() {

    return Long.toHexString(Long.parseLong(this.getRepresentacionBinaria(), 2));
}

getRepresentacionBinaria() generates a random string of 40 characters(0s and 1s), I need that string to be a Hexadecimal string(without the x), this code does it, the problem comes when Long.parseLong() parses the string and returns a hexadecimal number with leading zeros(which I need) and gives me this error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9

You can try the following function that convers long (many character) strings to hex strings (The String ss passed to function can be of the form "...0010..1.." that is "0" and "1" characters.

public String gettohexastring (String ss) 
{
 String toBuild="";
 String toRet="";
 int endi=ss.length();
 int begi=endi;
 for(int ii=0;ii<ss.length()-4;ii+=4)
 {
      endi=ss.length()-ii;
      begi=endi-4;
     String test=ss.substring(begi, endi);
     toBuild +=Long.toHexString(Long.parseLong(test),2);
 }
 endi=begi;
 begi=0;
 toBuild +=Long.toHexString(Long.parseLong(ss.substring(begi,endi),2));
 //To Reverse hex symbols
 for(int ii=toBuild.length();ii>=1;ii--)
 {
     toRet +=toBuild.substring(ii-1, ii);
 }
 return toRet;
}

To adapt this method to your quoted code you need to add this method to your class (simply by adding it as a public method to the rest of the public methods you quoted) and you may also have to change the last method you quoted to that:

public String getRepresentacionHexadecimal() {

return this.gettohexastring(this.getRepresentacionBinaria());

}

I also can mention that you may have to add a parethensis in your quoted method's code public String getRepresentacionBinaria()... at the line return this.representacionBinaria ; if representacionBinaria represents a method or function change it to ...this.representacionBinaria(); Hope the above will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM