-
August 4th, 2012, 02:51 AM
#1
Convert ascii to hex
Is there any code for converting ascii value to hex?
For example converting 65(ascii of "A") to 41(hex)
-
August 5th, 2012, 02:41 PM
#2
Re: Convert ascii to hex
Not sure I understand what you'd like to do. It sounds like you want to take the string "A" and convert it to the string "41". Is that correct?
If so, then there are a couple of steps:
1. convert the string to an integer
2. convert the integer to a string in a different format
For Example:
Code:
static string StringToHexValues(string input)
{
if (input == null)
throw new ArgumentNullException("input");
StringBuilder sb = new StringBuilder();
foreach (char c in input)
{
// Step 1: Convert to numeric type
// NOTE: If you know 'input' is an ASCII string, then
// you can use a byte. However in C# you never can garuntee that...)
int charVal = (int)c;
// Step 2: Convert to string in hex format
// NOTE: The "CultureInfo" isn't really necessary
// in this case, but its always a good habit be explicit...
string hexVal = charVal.ToString("X", CultureInfo.InvariantCulture);
sb.Append(hexVal);
sb.Append(" ");
}
return sb.ToString();
}
To see how this works:
Code:
Console.WriteLine(StringToHexValues("Hello World!"));
Console.WriteLine(StringToHexValues("您好世界"));
Produces
Code:
48 65 6C 6C 6F 20 57 6F 72 6C 64 21
60A8 597D 4E16 754C
Hope this helps
Last edited by enfekted; August 5th, 2012 at 02:45 PM.
-
August 5th, 2012, 04:09 PM
#3
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|