Click here to Skip to main content
15,900,384 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello I have a string in ascii and need to be transformed into hex
example :
asci :"
<stx><stx>000000000001000<fs>1000<fs><fs>+0<fs>941<fs><fs><fs><fs><fs><fs><fs><fs><fs><fs><fs>00<fs><fs><fs><etx> "

need convert in :
hex :"
02 02 30 30 30 30 30 30 30 30 30 30 30 31 30 30 30 1C 31 30 30 30 1C 1C 2B 30 1C 39 34 31 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 30 30 1C 1C 1C 03 14
I have not found any way that the result is of this form "
02 02 30 30 30 30 30 30 30 30 30 30 30 31 30 30 30 1C 31 30 30 30 1C 1C 2B 30 1C 39 34 31 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 30 30 1C 1C 1C 03 14

thank you and wait for your answer

What I have tried:

C#
public static string ConvertStringToHex(string asciiString)
        {
            string hex = "";
            foreach (char c in asciiString)
            {
                int tmp = c;
                hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }
but the result is : >
3c5354583e3c5354583e3030303030303030303030313130303c46533e313233343c46533e3c46533e2b303c46533e3934313c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e30303c46533e3c46533e3c46533e3c4554583e
I need :
02 02 30 30 30 30 30 30 30 30 30 30 30 31 30 30 30 1C 31 30 30 30 1C 1C 2B 30 1C 39 34 31 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 1C 30 30 1C 1C 1C 03 14
Posted
Updated 2-Jul-18 4:19am
v2

If you need to use actual text, like "<stx>", in your string to represent a control character, as other solutions have suggested, you'll need to write a parser.

If, instead, you are unfamiliar with representing them in C# strings, you can use the following:
C#
ConvertStringToHex("\x0002\x0002000000000001000\x001C1000\x001C\x001C+0\x001C941\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C00\x001C\x001C\x001C\x0003")
Assuming your string is truly limited to code points from 0-255, and you don't need to parse text like "<stx>", the following will do what you need:
public static string ConvertStringToHex(string asciiString)
{
  var builder = new StringBuilder(asciiString.Length * 3);
  foreach (char c in asciiString)
    if (c < byte.MinValue || c > byte.MaxValue)
      throw new ArgumentException(null, nameof(asciiString));
    else
      builder.AppendFormat("{0:X2} ", (byte)c);
  if (builder.Length > 0)
    builder.Length--;
  return builder.ToString();
}
There are a few things to note in this code.

First, your original code built a string by repeated concatenation. This is a bad idea. A string builder is much more efficient for this sort of operation.

Second, your original code jumped through an awful lot of hoops to get a number from a character. This is unnecessary. You can directly cast a char to most numeric types.

Finally, just in case code points beyond the 0-255 range slip into one of your strings, I added a check and throw an exception to alert the consumer.
 
Share this answer
 
v4
That doesn't work because the original string contains the textual representation of the control ASCII codes (instead of the actual ones). You have to properly parse it.
 
Share this answer
 
You can use regex to split the text into sections of codes and non-codes then parse them accordingly

string ascii = @"<stx><stx>000000000001000<fs>1000<fs><fs>+0<fs>941<fs><fs><fs><fs><fs><fs><fs><fs><fs><fs><fs>00<fs><fs><fs><etx>";

// match any chars in angle brackets, or any groups that are numbers or +
Regex r = new Regex(@"([<]\w+[>]|[\d|+]+)");

MatchCollection mc = r.Matches(ascii);

StringBuilder result = new StringBuilder();

// go through the results
foreach(Match m in mc)
{
    string v = m.Value;

    if (v.StartsWith("<") && v.EndsWith(">"))
    {
        // if it's a code (eg <stx>) use ConvertCodeToHex
        result.Append(ConvertCodeToHex(v));
    }
    else
    {
        // if it's not a code use ConvertStringToHex
        result.Append(ConvertStringToHex(v));
    }
}

string hex = result.ToString();


Now you just need to implement ConvertCodeToHex (there might be a function that does this already)

public static string ConvertCodeToHex(string code)
{
    // add the remaining cases
    switch (code.ToLower())
    {
        case "<stx>":
            return "02";
        default:
            return code;
    }
}
 
Share this answer
 
Your problem is that your string is escaped to show you non printable chars.
every char with an ascii value between 0 and 31 is non printable and is showed to you as '<??>' the inner code telling you which code it is.
In order to print the string in hex, you have basically 3 options:
- work with non escaped string in first place.
- reconvert the escaped string to its original form (binary), then print
- handle escaped chars on fly while printing

In order to get the output format you want, you need to add a space between each hex:
C#
public static string ConvertStringToHex(string asciiString)
        {
            string hex = "";
            foreach (char c in asciiString)
            {
                int tmp = c;
                // pay attention to the space at the end of format
                hex += String.Format("{0:x2} ", (uint)System.Convert.ToUInt32(tmp.ToString()));
            }
            return hex;
        }

The only problem is a space at the end of string, to solve it, you need a for loop.
C#
public static string ConvertStringToHex(string asciiString)
        {
            int tmp = asciiString[0];
            string hex = String.Format("{0:x2}", tmp);
            for (int scan= 1; scan<asciiString.length; scan++)
            {
                int tmp = asciiString[scan];
                hex += String.Format(" {0:x2}", tmp);
            }
            return hex;
        }
 
Share this answer
 
v2

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