XOR函数用于两个十六进制字节数组 [英] XOR function for two Hex byte arrays

查看:335
本文介绍了XOR函数用于两个十六进制字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图执行独占或两个字节数组并将结果作为十六进制字符串返回。我已经将两个字节数组转换为相应的二进制字符串。每个字节都有8位字节。

I am trying to perform the exclusive or of two byte arrays and return the result as a hex string. I have converted the two byte array to their corresponding binary string. Each byte will have bits since it has 8 bytes.

byte[] key =  { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };
byte[] PAN =  { 0x12, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x23 };

到现在为止,我已经使用了一种方法将字节数组转换为相应的二进制字符串值, 10101010101。然而,当我执行下面的方法来获得XOR时,我会返回一串笑脸,这可能是一些特殊的ASCII字符。

Until now I have used a method that transforms the byte array into their corresponding binary string value, e.g. "10101010101". However when I perform the below method to get the XOR I am being returned with a string of bunch of smiley face which probably is some special ASCII character.

但是,没有任何想法我可以做到这一点。我正在考虑将二进制字符串转换为整数,但这不是一个好的解决方案,因为它不适合作为整数。

However I don't have any ideas how I can do this. I was thinking to convert the binary string to an integer, but that is not a good solution since it will not fit as an integer.

你有什么想法,请?可能带有一些示例代码?

Do you have any ideas, please? possibly with some sample code?

public static string exclusiveOR(string string_1, string string_2)
{
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < string_1.Length; i++)
        sb.Append((char)(string_1[i] ^ string_2[(i % string_2.Length)]));
        String result = sb.ToString();

        return result;
}


推荐答案

你的代码 XOR 这两个字符串的字符,如果第一个字符串是较长的那个字符,则绕过第二个字符。

You are doing this correctly - your code XORs characters of the two strings, wrapping around the second one if the first one happens to be the longer one.

然而,异或的性质是只有不同的位保留在输出中。因此,当XOR 0x11 0x12 时,最终会出现 0x03 ,当在控制台上显示时,看起来像一颗心

However, the property of XOR is such that only the bits that are different remain set in the output. Hence, when you XOR 0x11 and 0x12, you end up with 0x03, which looks like a heart when displayed on a console.

这篇关于XOR函数用于两个十六进制字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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