Should be a simple conversion!!

  • Thread starter Thread starter Russ
  • Start date Start date
R

Russ

Hi guys & gals
I need to convert, in C#, a decimal hex string into an ascii string
(ie "56" -> "V"), and I can't find anything in the vs2003 help files
that is remotely helpful. Any suggestions that will save me writing my
own convert function would be gratefully received!
 
Russ said:
Hi guys & gals
I need to convert, in C#, a decimal hex string into an ascii string
(ie "56" -> "V"), and I can't find anything in the vs2003 help files
that is remotely helpful. Any suggestions that will save me writing my
own convert function would be gratefully received!

Is it always a single character? If so, use:

char c = (char) int.Parse(originalString);
 
Hi Jon,
No, this doesn't work I'm afraid. It converts 56 to "8" rather than
"V", so it is obviously thinking that the 56 is decimal, not hex. Any
ideas please?
Russ
 
Is it always a single character? If so, use:
char c = (char) int.Parse(originalString);

that will convert it from ASCII int to CHAR.
Try out this
char c = (char)int.Parse("56",System.Globalization.NumberStyles.HexNumber);
 
Russ said:
No, this doesn't work I'm afraid. It converts 56 to "8" rather than
"V", so it is obviously thinking that the 56 is decimal, not hex. Any
ideas please?

Ah, I was confused by your use of "decimal hex string" in the original
post. I didn't see the "hex" bit, just the "decimal" bit (and didn't
check the code for 'V').

In that case, use int.Parse(text, NumberStyles.HexNumber) (and cast to
char as before).

Alternatively, use Convert.ToInt32(text, 16) (and cast).
 
Thanks guys for your virtually identical solutions. This worked well
I ended up putting it into a loop to get the whole string thus :-

string type = "";
for(int i=0;i<= hexstring.Length-1;i=i+2)
{
type = type + (char)int.Parse(hexstring.Substring(i,2),

NumberStyles.HexNumber);
}

(And, yes, I know that I should have used stringbuilder, but I will
tidy up later!!)
Russ
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top