且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-03-21 04:57:52

处理 XOR 后,您将处理可能不是可打印 ASCII 字符的二进制字节.

Once you are dealing with XOR, you are dealing with binary bytes that might not be printable ASCII characters.

当你将相同的字符相互异或时,你会得到一个 0.所以 'P' ^ 'P' 将是 0.这是一个 NUL 字节,它终止了字符串.如果您尝试使用 printf() 进行打印,您将一无所获;printf() 认为该字符串是一个终止的长度为 0 的字符串.

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.

此外,您应该使用 = 将 XOR 结果分配到目标缓冲区,而不是像您的程序那样使用 ^=.

Also, you should simply assign the XOR result into your target buffer with = rather than using ^= as your program did.

这是我的程序版本,以及我的输出:

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
PlainText Two: %s

one^two: ", plainone, plaintwo);
    for(i=0; i<LENGTH; ++i)
        printf("%02X ", xor[i]);
    printf("
");
    return 0;
}

输出:

PlainText One: PlainOne
PlainText Two: PlainTwo

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

注意前五个字节都是 00 因为 PlainPlain 异或.

Notice how the first five bytes are all 00 because Plain is XORed with Plain.