C语言 如何按位异或两个 C 字符数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27914271/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:41:36  来源:igfitidea点击:

How can I bitwise XOR two C char arrays?

carrayscharbit-manipulationxor

提问by Matthew Darnell

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 数组不读取任何内容?

回答by steveha

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. If you try to print with printf()you get nothing; printf()considers the string to be a terminated length-0 string.

当你对相同的字符进行异或时,你会得到一个 0。所以'P' ^ 'P'将是 0。这是一个 NUL 字节,它终止了字符串。如果您尝试打印,则printf()一无所获;printf()将字符串视为终止的长度为 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 00because Plainis XORed with Plain.

请注意前五个字节是如何全部00因为PlainPlain.

回答by naasking

Well "Plain" xor "Plain" == 00000, were 0 is the terminator char. C strings print up to the terminator, which means it prints nothing.

那么“Plain”xor“Plain”==00000,0是终止符字符。C 字符串打印到终止符,这意味着它不打印任何内容。