Monday, May 31, 2010

Hex to ASCII and ASCII to Hex in JAVA


"HEX to ASCII Conversion in JAVA":

public static String hexToASCII(String hex){       
          if(hex.length()%2 != 0){
             System.err.println("requires EVEN number of chars");

             return null;
          }
          StringBuilder sb = new StringBuilder();               
          //Convert Hex 0232343536AB into two characters stream.
          for( int i=0; i (LessThan) hex.length()-1; i+=2 ){

               /*
                * Grab the hex in pairs
                */

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

              /*
               * Convert Hex to Decimal
               */

              int decimal = Integer.parseInt(output, 16);                 
              sb.append((char)decimal);             
          }           
          return sb.toString();
    }


"ASCII to Hex Conversion In JAVA" :

public static String asciiToHex(String ascii){
        StringBuilder hex = new StringBuilder();
       
        for (int i=0; i < ascii.length(); i++) {
            hex.append(Integer.toHexString(ascii.charAt(i)));
        }      
        return hex.toString();
    } 

5 comments:

Anonymous said...

Thanks..!!

Sujit said...

Thank you very much..You helped a lot..!!!

Sujit said...

Thank you very much..You helped a lot..!!!

Sham said...

how can i print the hex values in some format like this
ascii value
******-******-******
converted hex value
************************************************
format to be printed
0x****
0x****
.
.
0x**
how can i do this?any help?

Sham said...
This comment has been removed by the author.