Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,

I'm using the following code to convert a string to hex:

C#
char[] charArray = plainText.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int num;
            string hex;
            for (int i = 0; i < charArray.Length; i++)
            {
                num = Convert.ToInt32(charArray[i]);
                hex = num.ToString("x");
                sb.Append(hex);
            }

The problem here is that, this code is converting all the line feeds into DA instead of 0A. According to the ASCII table to HEX:

DA - Ú
0A - linefeed

Does anyone got an idea about how can I convert the line feeds correctly?? Thanks, Nuno.
Posted

No it isn't: Look more closely and you will see it is actually outputting two values: "D" for Carriage return and "A" for Line feed.
To prove it, add a comma to each sb.Append.
 
Share this answer
 
Hi,
This is probably a formatting issue and what you are seeing is a carriage return (0xD) followed by a line feed(0xA). When num is < 0x10 ToString("x") will output only one character. "x2" will ensure that the output is padded with leading zeroes to a length of 2.

Numeric format strings[^]

Alan.
 
Share this answer
 
Comments
Dalek Dave 12-Oct-10 10:03am    
That is a good Answer
It is in fact true that using "x2" in the ToString method, converts the string correctly.

Thanks!
 
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