简体   繁体   English

如何对两个C字符数组按位进行XOR?

[英]How can I bitwise XOR two C char arrays?

I feel silly for not being able to figure this out, but I am lost. 无法解决这个问题,我感到很傻,但是我迷路了。 I am trying to XOR two C strings. 我试图XOR两个C字符串。

#include <stdio.h>
#include <memory.h>
#include <stdlib.h>
int main()
{
    char plainone[16]; 
    char plaintwo[16];
    char xor[17];
    strcpy(plainone, "PlainOne");
    strcpy(plaintwo, "PlainTwo");
    int i=0;
    for(i=0; i<strlen(plainone);i++)
        xor[i] ^= (char)(plainone[i] ^ plaintwo[i]);
    printf("PlainText One: %s\nPlainText Two: %s\n\none^two: %s\n", plainone, plaintwo, xor);
    return 0;
}

My output is: 我的输出是:

$ ./a.out 
PlainText One: PlainOne
PlainText Two: PlainTwo

one^two: 

Why doesn't the xor array read as anything? 为什么xor数组不读取任何内容?

Once you are dealing with XOR, you are dealing with binary bytes that might not be printable ASCII characters. 一旦处理了XOR,就将处理可能不是可打印ASCII字符的二进制字节。

And when you XOR the same characters with each other, you get a 0. So 'P' ^ 'P' will be 0. That's a NUL byte and it terminates the string. 当您对相同的字符进行XOR运算时,您将得到0。因此'P' ^ 'P'将为0。这是一个NUL字节,它终止了字符串。 If you try to print with printf() you get nothing; 如果您尝试使用printf()打印,您将一无所获。 printf() considers the string to be a terminated length-0 string. printf()认为该字符串是终止的length-0字符串。

Also, you should simply assign the XOR result into your target buffer with = rather than using ^= as your program did. 同样,您应该仅使用=将XOR结果分配到目标缓冲区中,而不是像程序那样使用^=

Here's my version of your program, and my output: 这是我的程序版本,以及我的输出:

#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

#define LENGTH 16
int main()
{
    char const plainone[LENGTH] = "PlainOne";
    char const plaintwo[LENGTH] = "PlainTwo";
    char xor[LENGTH];
    int i;

    for(i=0; i<LENGTH; ++i)
        xor[i] = (char)(plainone[i] ^ plaintwo[i]);
    printf("PlainText One: %s\nPlainText Two: %s\n\none^two: ", plainone, plaintwo);
    for(i=0; i<LENGTH; ++i)
        printf("%02X ", xor[i]);
    printf("\n");
    return 0;
}

Output: 输出:

PlainText One: PlainOne
PlainText Two: PlainTwo

one^two: 00 00 00 00 00 1B 19 0A 00 00 00 00 00 00 00 00

Notice how the first five bytes are all 00 because Plain is XORed with Plain . 注意前五个字节都是00因为Plain是与Plain异或的。

Well "Plain" xor "Plain" == 00000, were 0 is the terminator char. 那么“ Plain” xor“ Plain” == 00000,分别是0是终止符char。 C strings print up to the terminator, which means it prints nothing. C字符串打印到终止符,这意味着它什么也不打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM