Solved

# Hexa to Ascii convertion

Posted on 2008-11-19
1,337 Views
How can i write a function that takes an hexa aas String and returns me the ascii representation of the number(as char).

Ex:   convert("4B") -> 'K'
0
Question by:kodcanavari

LVL 24

Expert Comment

A character in JAVA is 16 bits, however common ascii is converted by adding 8 0-bits in front.

You might convert that HEX string by parsing to a short, and adding the zero bits in front
as a char is unsigned in JAVA.

;JOOP!
0

LVL 24

Expert Comment

public char convert(String hex)
{
int h = Integer.parseInt(hex, 16);
char c = (h & 0377);

return(c);
}

;JOOP!
0

LVL 24

Expert Comment

char c = (h & 0377);  // Will give a compiler warning, better is:

public char convert(String hex)
{
int h = Integer.parseInt(hex, 16);
return((char)(h & 0377));
}

;JOOP!
0

LVL 24

Expert Comment

And beware of NumberFormatExceptions when junk string is given ......................

;JOOP!
0

LVL 6

Expert Comment

``````char val = (char)Integer.valueOf("4B", 16).intValue();
``````
0

LVL 1

Author Comment

first thant for the response, it corresponds exactly. As you

if i write this char to a file how many bites will it be?
is there any way to write the value of the hexa on a file?
4B -> 01001011 (on the file system)
0

LVL 1

Author Comment

i wanted to say thanks on the 1st line
0

LVL 6

Accepted Solution

If you want to write exactly the ones and zeroes on a text file or the console you can do as so:

``````int hexVal = Integer.valueOf("4B", 16).intValue();

char val = (char)hexVal;

String st = Integer.toBinaryString(hexVal);

//Writing to the console...

System.out.println(val);

System.out.println(st);
``````
0

LVL 1

Author Closing Comment

Thats exactly what i want, thanks a lot.
0

LVL 24

Expert Comment

0

## Featured Post

Iteration: Iteration is repetition of a process. A student who goes to school repeats the process of going to school everyday until graduation. We go to grocery store at least once or twice a month to buy products. We repeat this process every montâ€¦
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different dâ€¦
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.