Java解密代码转C#失败求助:修复代码转换后的报错问题
Let's walk through each error you're facing, fix them, and also correct a critical logic mistake that would have broken decryption even if the compiler errors were resolved:
Error 1: 'string' does not contain a definition for 'valueOf'
Java's String.valueOf() method doesn't exist in C#. Instead of converting the character to a string then parsing it to an integer, you can directly cast the char to an int to get its ASCII/Unicode numeric value. This achieves exactly what your Java code does (since Integer.parseInt(String.valueOf(str.charAt(i))) ultimately retrieves the character's numeric value).
Errors 2 & 3: int.Parse argument mismatches
Two key issues here:
- C# Substring behavior differs: Java's
substring(startIndex, endIndex)uses start and end positions (exclusive of the end), but C#'sSubstring(startIndex, length)takes a start position and the number of characters to extract. Your Java code grabs 2 characters (fromi+1toi+3), so in C# you needstr.Substring(i + 1, 2). - Parsing hexadecimal strings: To parse a hex string to an int in C#, use
Convert.ToInt32(hexString, 16)—this is the direct equivalent of Java'sInteger.parseInt(hexStr, 16). Theint.Parseoverload you tried expects a culture format provider, not a numeric base, which is why those errors appeared.
Critical Logic Mistake
You accidentally swapped Java's XOR operator (^) with C#'s OR operator (|). These are entirely different operations—XOR is required for your decryption logic to work as intended.
Corrected C# Code
Here's the fixed button click handler:
private void button1_Click(object sender, EventArgs e) { string str = "575-371-46b-576-362-276-528-634-731-330-53c-729-436"; str = str.Replace("-", ""); string result = ""; for (int i = 0; i < str.Length; i += 3) { // Get numeric value of the first character in the 3-character group int charValue = (int)str[i]; // Parse the next two characters as a hexadecimal integer int hexValue = Convert.ToInt32(str.Substring(i + 1, 2), 16); // Perform XOR and convert the result back to a character result += (char)(hexValue ^ charValue); } textBox1.Text = result; }
When you run this code, it will correctly decrypt your string to the expected readable result.
内容的提问来源于stack exchange,提问作者amr selim

