我有一个关于 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/