简体   繁体   English

C#:具有重新定义的十六进制值的文本到十六进制的转换

[英]C# : Text to Hex conversion with redefined hex values

I am attempting to write a program that will convert ASCII text to hex values. 我正在尝试编写一个将ASCII文本转换为十六进制值的程序。 The issue is that I am working with a project that uses a different hex value for ASCII characters than the standard, so I have to incorporate the predefined character set (using 'static Dictionary') into the conversion. 问题是我正在一个项目中使用与标准字符不同的ASCII字符十六进制值,因此我必须将预定义的字符集(使用“静态字典”)合并到转换中。

My intention is to have it setup with 2 text boxes, one where I type to ASCII out and another where it prints the hex values. 我的意图是使用2个文本框进行设置,一个文本框输入ASCII输出,另一个文本框输出十六进制值。

If I type in the ASCII string "Jack", I would want a window to return 4b 62 64 6c. 如果输入ASCII字符串“ Jack”,则希望窗口返回4b 62 64 6c。 (Yes, all the hex values are shifted by one, don't ask.... Not my call) (是的,所有十六进制值都移位了一个,不要问。。。不是我的电话)

I'm unsure how to do this and force it to use the values defined by static Dictionary. 我不确定如何执行此操作,并强制其使用静态词典定义的值。

Define you dictionary as Dictionary<char, int> and have each char as the key and the modified hex value as the value . 将您的字典定义为Dictionary<char, int>并将每个char作为键,并将修改后的十六进制值作为value

That way when you convert, you simply lookup the hex value in the dictionary. 这样,在转换时,您只需在字典中查找十六进制值。

var x = MyStrangeHexValuesThatWeShouldntAskAbout[myChar];

This solution only works for ASCII characters: 此解决方案仅适用于ASCII字符:

public static string ToMySpecialAsciiString(string input)
{
    StringBuilder result = new StringBuilder();

    foreach (char c in input)
        result.AppendFormat("{0:x2} ", c + 1);

    return result.ToString();
}

Note that the character ÿ will not work properly (because it has value 255, and adding 1 to it will overflow a byte). 请注意,字符ÿ不能正常工作(因为它的值为255,并向其加1将溢出一个字节)。 However since you specify ASCII only, that character will never occur. 但是,由于仅指定ASCII,因此永远不会出现该字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM