Search code examples
cbytexor

Performing XOR byte comparisons with chars


I'm trying to perform an XOR byte operation on every 3rd byte in an unsigned char array in my program. I'm having a type conversion error occur when I attempt to compile the program.

my declarations

unsigned char *s;
FILE *fp;
char ch;
int count = 0;
unsigned char *load = malloc(sizeof(char));
int i = 0;

s = "s";

and this is where the error is occurring...

for (i = 3; i < count;)
{
    temp = (load[i-1] ^ s);
    temp2 = (load[i] ^ s);
            i = i + 3;
}       

once I can get the XOR operation to work, I'll be setting load[i-1] = temp, right now I'm just trying to get the operation to compile and hopefully work.

Thanks in advance for any help / insight.

EDIT* Updated to give temp data type and show how unsigned char *load = malloc(sizeof(char)) is being used to take from data from a file.

char temp, temp2;


while ((ch = fgetc(fp)) != EOF)
{
    load[i++] = ch;
}

and here is the error it is producing...

main.c:14:4: warning: assigning to 'unsigned char *' from 'char [2]' converts between pointers to integer types with different sign [-Wpointer-sign]

    s = "s";
      ^ ~~~

main.c:86:21: error: invalid operands to binary expression ('int' and 'unsigned char *')

            temp = (load[i-1] ^ s);
                    ~~~~~~~~~ ^ ~

main.c:87:20: error: invalid operands to binary expression ('int' and 'unsigned char *')

            temp2 = (load[i] ^ s);

Solution

  • You are allocating memory to hold only one unsigned char in

    unsigned char *load = malloc(sizeof(char));
    

    Then you are trying access the third character using load[i-1].

    Update

    The compiler error is very clear about the nature of the error

    main.c:86:21: error: invalid operands to binary expression ('int' and 'unsigned char *')
    
            temp = (load[i-1] ^ s);
    

    Perhaps you meant to use:

            temp = (load[i-1] ^ s[0]);
    

    About the other compiler message, you can take care of that by initializing s when it is defined.

    unsigned char *s = "S";
    

    instead of assigning to it later.