XOR-in Strings in C #

I recently started playing with C #, and I'm trying to understand why the following code does not compile. In the line with the comment about the error, I get:

It is not possible to implicitly convert the type 'int' to 'char'. Explicit conversion terminates (are you skipping listing?)

I am trying to perform a simple XOR operation with two lines.

public string calcXor (string a, string b) { char[] charAArray = a.ToCharArray(); char[] charBArray = b.ToCharArray(); char[] result = new char[6]; int len = 0; // Set length to be the length of the shorter string if (a.Length > b.Length) len = b.Length - 1; else len = a.Length - 1; for (int i = 0; i < len; i++) { result[i] = charAArray[i] ^ charBArray[i]; // Error here } return new string (result); } 
+8
source share
3 answers

You make 2 characters xor . This will result in an implicit type conversion to int for you, since there is no data loss. However, converting from int to char will require you to cast explicitly.

You need to explicitly convert your int to char for result[i] :

 result[i] = (char) (charAArray[i] ^ charBArray[i]); 
+4
source

If you use XOR-ing to hide data, look at the code below. The key will be repeated as long as necessary. This is possibly a shorter / better approach:

 public static string xorIt(string key, string input) { StringBuilder sb = new StringBuilder(); for(int i=0; i < input.Length; i++) sb.Append((char)(input[i] ^ key[(i % key.Length)])); String result = sb.ToString (); return result; } 
+16
source

If the meaning of the result is important, then Allan is right (accepted answer). If you're just looking for a match and not worried about performance, use the alternative to strcmp () or memcmp ().

In assembler, it is common to initialize XOR things against themselves, since T-loops are smaller. If I were crude forcing (hash comparison), then this would be an improvement over strcmp or memcmp, since I really don't sort the order, I just map / number.

Readers should also know this one that can be customized.

0
source

All Articles