java - OC异或和Java异或有什么区别?

标签 java ios objective-c xor

我有一个关于 Java 和 OC xor 的问题:

第一个异或,第二个Base64

在java中,代码:

     String  numberStr = ("123456");

    char[] array = numberStr.toCharArray();
    for (int i = 0; i < array.length; i++)
    {
        array[i] = (char) (array[i] ^ 1984);
    }
    String xorStr = new String(array);


    byte[] b = null;
    String s = null;
    try {
        b = xorStr.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (b != null) {
        try {
            s = Base64.encodeToString(b, Base64.DEFAULT);;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
    }

结果是:37Hfst+z37Tftd+2

在OC中,代码:

    NSString *numberString = @"123456";
    NSData* bytes = [numberString dataUsingEncoding:NSUTF8StringEncoding];
    int8_t * bytePtr = ( int8_t * )[bytes bytes];
    NSInteger totalData = [bytes length] / sizeof(int8_t);
    NSMutableString *finalString = [NSMutableString new];
    for (int i = 0 ; i < totalData; i ++){
    bytePtr[i] = (int8_t)(bytePtr[i]) ^ (1984);
    [finalString appendString:[NSString stringWithFormat:@"%c",bytePtr[i]]];
    NSLog(@"encrypt data = %d", bytePtr[i]);
    }

    NSData *finalData = [finalString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *baseString = [finalData base64EncodedStringWithOptions:0];

结果 baseString 是:w7HDssOzw7TDtcO2

为什么结果不一样?我只知道我的 OC 代码是错误的! 谁能告诉我正确答案?

最佳答案

您没有使用彼此等价的类型。

来自 Java 规范:

"The char data type (and therefore the value that a Character object encapsulates) are based on the original Unicode specification, which defined characters as fixed-width 16-bit entities. The Unicode Standard has since been changed to allow for characters whose representation requires more than 16 bits. The range of legal code points is now U+0000 to U+10FFFF, known as Unicode scalar value. (Refer to the definition of the U+n notation in the Unicode Standard.)"

在您的 Java 代码中,您正在迭代 16 位对象。在 OC 代码中,您正在迭代 8 位对象。

对于 8 位 Java 基本类型,使用 byte

关于java - OC异或和Java异或有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47291514/

相关文章:

java - 每次跳过该方法时都使用 TestNG 符号,例如 @parameters 或 @dataprovider...

java - 将 WebElement 的属性值存储在 Selenium Webdriver 中

java - 使用正则表达式从文本文件中剥离数据

ios - ConvertPoint 没有返回我想要的值

iphone - 将 UILabel 添加到 UIImageView

java - 具有不同值的哈希表相同的键....?

ios - ARKit 变换矩阵中的值代表什么?

ios - 如何在 iOS 7 和 iOS 8 上正确自定义 UITabBar 和 UITabBarItem?

ios - 子类化 UIPageViewController,但是当我将 [[alloc] init] 的结果分配给自己时,我收到警告。为什么?

iphone - 如何更改 ui 导航 Controller 后退按钮操作