我试图扭转一种方法,但实际上我已经被困了几天了。我不知怎的再也无法绕过这段代码...似乎有些愚蠢的心理障碍。
public string HexValueToStringValue(string myString, int pattern = 196) {
pattern = pattern % 0x100;
string myReturnString = "";
for (int x = 1; x <= myString.Length; x += 2)
{
myReturnString = myReturnString + Conversions.ToString(Strings.Chr(Convert.ToInt32(Strings.Mid(myString, x, 2), 0x10) ^ pattern));
int test = Convert.ToInt32(Strings.Mid(myString, x, 2), 0x10) + 1;
pattern = test % 0x100;
}
return myReturnString;
}
我只想要与给定方法完全相反。我想使用给定的算法从常规字符串创建十六进制字符串。 任何帮助将不胜感激。
猜猜现在是时候对这种方法进行一些重构了 - 但实际上我真的失去了对它的追踪......
答案 0 :(得分:1)
我重构了你的代码并编写了相反的方法。
正如我在评论A ^ B == B ^ A
和A ^ B ^ B == A
中所写,所以test = test ^ pattern; test = pattern ^ test;
没用,因为它等同于test = test ^ pattern; test = test ^ pattern
,这相当于到test = test ^ pattern ^ pattern
。
public static string HexValueToStringValue(string hex, int pattern = 196)
{
pattern = pattern % 0x100;
var sb = new StringBuilder(hex.Length / 2);
for (int i = 0; i < hex.Length; i += 2)
{
string h = hex.Substring(i, 2);
int val = Convert.ToInt32(h, 16);
char ch = (char)(val ^ pattern);
sb.Append(ch);
pattern = (val + 1) % 0x100;
}
return sb.ToString();
}
public static string StringToHexValue(string str, int pattern = 196)
{
pattern = pattern % 0x100;
var sb = new StringBuilder(str.Length * 2);
for (int i = 0; i < str.Length; i++)
{
char ch = str[i];
int val = ch ^ pattern;
string h = val.ToString("X2");
sb.Append(h);
pattern = (val + 1) % 0x100;
}
return sb.ToString();
}