Leon Anavi
IT Tips && Tricks


Created: 29.07.2009 10:13 Last Modified: 01.09.2009 22:07 Views: 13121
Keywords: ascii, convert, dec, hex

Convert Text to Hex


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.


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));
            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( sTextAsHex );
        catch (IOException Ex)


Class Reference

Class String

  Home | About | Contact | Disclaimer | Sitemap 2009-2022 Leon Anavi. All rights reserved.