C#我在ascii中有一个字符串,需要转换为十六进制 [英] C# I have a string in ascii and need to be transformed into hex

查看:986
本文介绍了C#我在ascii中有一个字符串,需要转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在ascii中有一个字符串,需要转换为十六进制

示例:

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>



需要转换为:

hex:

 02 02 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 30 30 1C 1C 1C 03 14 

我没有发现结果是这种形式的任何方式

 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 30 30 1C 1C 1C 03 14 



谢谢你,等待你的回答



我的尝试:



  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;
}

但结果是产品:> <预郎= 文本> 3c5354583e3c5354583e3030303030303030303030313130303c46533e313233343c46533e3c46533e2b303c46533e3934313c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e3c46533e30303c46533e3c46533e3c46533e3c4554583e

我需要:<预郎= 文本> 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 30 30 1C 1C 1C 03 14

解决方案

如果您需要在字符串中使用实际文本,例如< stx>来表示控制字符,正如其他解决方案所建议的那样,我需要编写一个解析器。



如果你不熟悉用C#字符串表示它们,你可以使用以下内容:

 ConvertStringToHex(  \ x0002 \ x0002000000000001000 \ x001C1000 \ x001C \\ \\x001C + 0\\ \\x001C941\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C00\x001C\x001C\x001C\x0003\" 

假设您的字符串真正限制在0-255之间的代码点,并且您不需要解析像< stx>这样的文本,以下内容将满足您的需求:

 public static string ConvertStringToHex(string asciiString)
{
var builder = new StringBuilder(asciiString.Length * 3);
foreach(charc in asciiString)
if(c< byte.MinValue || c> byte.MaxValue)
抛出新的ArgumentException(null,nameof(asciiString));
else
builder.AppendFormat({0:X2},(byte)c);
if(builder.Length> 0)
builder.Length--;
返回builder.ToString();
}

此代码中有几点需要注意。



首先,您的原始代码通过重复连接构建了一个字符串。这是一个坏主意。字符串构建器对于这种操作来说效率更高。



其次,你的原始代码跳过了大量的箍来从一个角色获得一个数字。这是不必要的。您可以直接将 char 转换为大多数数字类型。



最后,以防万一代码点超出0 -255范围滑入你的一个字符串,我添加了一个检查并抛出异常以提醒消费者。


这不起作用,因为原始字符串包含控件的文本表示 ASCII 代码(而不是实际代码)。您必须正确解析它。


您可以使用正则表达式将文本拆分为代码和非代码的部分,然后相应地解析它们



 string ascii = @< stx>< stx> 000000000001000< fs> 1000< fs>< fs> + 0< fs> 941< fs>< fs>< FS>< FS>< FS>< FS>< FS>< FS>< FS>< FS>< FS> 00 LT; FS>< FS>< FS>< ETX> ; 

//匹配尖括号中的任何字符,或任何数字组或+
正则表达式r =新正则表达式(@([<] \w + [>] | [\d | +] +));

MatchCollection mc = r.Matches(ascii);

StringBuilder result = new StringBuilder();

//查看结果
foreach(mc中匹配m)
{
string v = m.Value;

if(v.StartsWith(<)&& v.EndsWith(>))
{
//如果是代码(例如< stx>)使用ConvertCodeToHex
result.Append(ConvertCodeToHex(v));
}
else
{
//如果它不是代码使用ConvertStringToHex
result.Append(ConvertStringToHex(v));
}
}

string hex = result.ToString();





现在你只需要实现ConvertCodeToHex(可能有一个函数已经这样做了)



 public static string ConvertCodeToHex(string code)
{
//添加其余案例
switch(code.ToLower())
{
case< stx>:
返回02 ;
默认值:
返回码;
}
}


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:

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

解决方案

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:

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.


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.


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;
    }
}


这篇关于C#我在ascii中有一个字符串,需要转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆