Click here to Skip to main content
15,903,012 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi All, I am new in c# programming and need to convert a string "1234ABCD" into "F1F2F3F4C1C2C3C4".Could you please suggest some good way for this.

Thnx,
adir
Posted
Comments
Sergey Alexandrovich Kryukov 13-Jul-12 20:16pm    
Do you like people to do guesswork?
--SA

Something like this[^].

By they way, had to guess that this is what you wanted: your question should really have been 'How do I convert an ASCII string to Hex?'. You should also learn to use Google.
 
Share this answer
 
First of all, you have the wrong code type. What you are converting to is the representations in EBCDIC (http://en.wikipedia.org/wiki/EBCDIC[^]), not ASCII (http://en.wikipedia.org/wiki/ASCII[^]) which is used by Microsoft, and on most other systems. The code I am providing will only convert the first 8 bits, not the full 16 bits, but can be fixed to do that if that is what you want:

C#
string testString = "1234ABCD";
var stringBuilder = new StringBuilder();
foreach (char chr in testString)
{
    var lft = ((int) chr & 240) / 16;
    stringBuilder.Append(ConvertNibbleToHex(lft));
    var rt = (int) chr & 15;
    stringBuilder.Append(ConvertNibbleToHex(rt));
}


This uses the following function:

C#
private static char ConvertNibbleToHex(int value)
{
    if (value < 10)
        return (char) (value + 48);
    return (char)(value + 55);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900