问题描述
我对无法解决这个问题感到很傻,但是我迷路了.我正在尝试对两个C字符串进行XOR.
I feel silly for not being able to figure this out, but I am lost. I am trying to XOR two C strings.
#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;
}
我的输出是:
$ ./a.out
PlainText One: PlainOne
PlainText Two: PlainTwo
one^two:
为什么xor数组不读取任何内容?
Why doesn't the xor array read as anything?
推荐答案
一旦处理了XOR,就将处理可能不是可打印ASCII字符的二进制字节.
Once you are dealing with XOR, you are dealing with binary bytes that might not be printable ASCII characters.
当您对相同的字符进行XOR运算时,您将获得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\nPlainText Two: %s\n\none^two: ", plainone, plaintwo);
for(i=0; i<LENGTH; ++i)
printf("%02X ", xor[i]);
printf("\n");
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
,因为Plain
与Plain
进行了异或.
Notice how the first five bytes are all 00
because Plain
is XORed with Plain
.
这篇关于如何对两个C字符数组按位进行XOR?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!