Introduction
A string is a sequence of symbols. The character encoding is based ot ASCII (American Standard Code for Information Interchange) and each character has an unique decimal(0-9) identification number. For example the acsii code for a is 97.
To convert a text (string) to hexadecimal(0-9, A, B, C, D, E, F) the ascii code of every symbol must be presented as two digit hexadecimal value. If the value length is less than two (i.e. length is one digit) then a zero has to be added as a prefix.
Example
The sample Java console application reads keyboard input and converts each symbol to hexadecimal value with appropriate format.
package hexconverter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author Leon Anavi
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
BufferedReader BufRdr = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter:");
try
{
String sText = BufRdr.readLine();
String sTextAsHex = "";
for(int nIter = 0; nIter < sText.length(); nIter++)
{
//Convert ascii to hex
String sHex = String.format("%02x", (int)sText.charAt(nIter));
sHex = sHex.toUpperCase();
sTextAsHex += sHex;
}
System.out.println();
System.out.println( sTextAsHex );
}
catch (IOException Ex)
{
System.out.println(Ex.getMessage());
}
}
}
Class Reference
Class String
|