Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XORing "Hello World!" cuts off string

Tags:

c++

c

xor

#include <stdio.h>
#include <string.h>

int main()
{
    char greeting[]="\nHello World!\n";
    int a;

    for(int i=0; i<strlen(greeting); i++)
        greeting[i]^=111;

    for(int i=0; i<strlen(greeting); i++)
        greeting[i]^=111;

    printf("%s\n",greeting);    
    scanf("%d",&a);

}

Output:

Hell

Why does it cut everything after spotting a letter corresponding to the XOR key's number (in this case, ASCII 'w')? In mathematical logic, N^N=0 and 0^N=N, doesn't it?

like image 219
0x6B6F77616C74 Avatar asked May 01 '12 00:05

0x6B6F77616C74


2 Answers

Because 'o' is ASCII code 111, and XORing 111 with 111 yields 0, NUL, and terminates your string. Once this happens (even in the first loop, since you're evaluating it each time through the loop), strlen reports the string is much shorter, and the loops stop.

Saving the string length before going through the XORs will save you from this.

like image 145
zigg Avatar answered Nov 16 '22 05:11

zigg


This is because when you xor a number with itself, it becomes zero, and when strlen sees zero, it thinks it's the end of the string.

If you store the length in a variable before the first loop and then use that saved length in your second loop instead of strlen, your program will produce the expected result.

like image 10
Sergey Kalinichenko Avatar answered Nov 16 '22 06:11

Sergey Kalinichenko