Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1344
  • Last Modified:

Hexa to Ascii convertion

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
kodcanavari
Asked:
kodcanavari
  • 5
  • 3
  • 2
1 Solution
 
sciuriwareCommented:
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
 
sciuriwareCommented:
public char convert(String hex)
{
     int h = Integer.parseInt(hex, 16);
     char c = (h & 0377);

    return(c);
}

;JOOP!
0
 
sciuriwareCommented:
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

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

;JOOP!
0
 
dnunes_brCommented:
This answers your question, I believe so:
char val = (char)Integer.valueOf("4B", 16).intValue();

Open in new window

0
 
kodcanavariAuthor Commented:
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
 
kodcanavariAuthor Commented:
i wanted to say thanks on the 1st line
0
 
dnunes_brCommented:
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);

Open in new window

0
 
kodcanavariAuthor Commented:
Thats exactly what i want, thanks a lot.
0
 
sciuriwareCommented:
The question was already answered!!!!!!!!!
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now