简体   繁体   中英

C# : Text to Hex conversion with redefined hex values

I am attempting to write a program that will convert ASCII text to hex values. 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.

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.

If I type in the ASCII string "Jack", I would want a window to return 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 .

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:

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). However since you specify ASCII only, that character will never occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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