Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use the XOR operator with two char's for some reason, does anyone get why?

Tags:

operators

c#

Is there some formal standards that do not allow one to use the ^ or XOR function in C# with two chars?

    public char[] XORinput(char[] input, char SN)
    {
        int InputSize = input.Length;
        //initialize an output array
        char[] output = new char[InputSize];

        for (int i = 0; i < InputSize; i++)
        {

            output[i] = input[i] ^ SN;

        }


        return output;

    }

For whatever reason this code is giving me this error, Error 1400 Cannot implicitly convert type 'int' to 'char'. An explicit conversion exists (are you missing a cast?)

This does not make any sense.

Caller:

                string num = "12345";
                char SN = Convert.ToChar(num);//serial number

                string sCommand = ("Hellow");

                char[] out = new char[sCommand.ToCharArray().Length];


                out = calculator.XORinput(sCommand.ToCharArray(), SN);
like image 398
Recurrsion Avatar asked Sep 21 '25 09:09

Recurrsion


2 Answers

The error is not with the function, but with the result of it.

When you do input[i] ^ SN; your result is an int, which you "Cannot implicitly convert type 'int' to 'char'.

You can cast it like this:

(char)(input[i] ^ SN);
like image 54
NominSim Avatar answered Sep 23 '25 01:09

NominSim


The xor operator (along with other operators) return an integer result. So a single cast to char is sufficient.

output[i] = (char)(input[i] ^ SN);

In this case you wouldn't have to cast, but it's less efficient in your case:

output[i] = input[i];
output[i] ^= SN;
like image 20
huysentruitw Avatar answered Sep 22 '25 23:09

huysentruitw