如何按位异或两个 C 字符数组? [英] How can I bitwise XOR two C char arrays?

查看:39
本文介绍了如何按位异或两个 C 字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我因为无法弄清楚这一点而感到愚蠢,但我迷路了.我正在尝试对两个 C 字符串进行异或运算.

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

one^two: %s
", 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.

当你将相同的字符相互异或时,你会得到一个 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.

这篇关于如何按位异或两个 C 字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆