java - Java中utf8字符串及其字节的编码和解码

标签 java string utf-8

我正在开发一个项目,需要在 java 中对字符串进行编码和编码。我的字符串是一个由波斯字符组成的 UTF-8 字符串。我只是想用静态字符对每个字节进行异或,然后用相同的静态字符再次进行异或。

我写了下面的代码,但它完全运行错误!我用英文字符检查了一下,它有效。

如何解决这个问题?

String str = "س";
char key = 'N';
byte bKey = (byte) key;

byte[] b = str.getBytes();

for (int i = 0; i < b.length; i++)
{
    b[i] = Byte.valueOf((byte) (b[i] ^ bKey));
}

String str1 = new String(b);
b = str1.getBytes();

for (int i = 0; i < b.length; i++)
{
    b[i] = (byte) (b[i] ^ bKey);
}

String str2 = new String(b);

最佳答案

当您从变异字节创建 str1 时,问题就出现了。假设您的默认编码是 UTF8,当您说 String str1 = new String(b); 时,您是在说这是 UTF8 编码中的一些字节,请为我构建一个漂亮的字符串。但是因为您对字节进行了异或,所以编码是无效的 UTF8,并且 Java 不太知道如何处理它。如果您查看使用 b = str1.getBytes(); 从 str1 检索的字节,您会发现它们与您创建字符串所用的字节不同!

真的,您不应该从“无意义”字节创建字符串——您真的需要将异或字节存储回字符串中吗?

如果您确实想这样做,您可以使用单字节编码来欺骗系统,其中所有可能的字节值都是有效的。然后您可以确定放入字符串中的字节与取出的字节相同。这是一个对我有用的示例:

public class B {
    static public void main(String[] args) throws Exception {
        String str = "س";
        System.out.println(str);
        char key = 'N';
        byte bKey = (byte) key;

        byte[] b = str.getBytes("UTF8");

        System.out.println("Original bytes from str:");
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i]);
        }

        System.out.println("Bytes used to create str1:");
        for (int i = 0; i < b.length; i++) {
            b[i] = Byte.valueOf((byte) (b[i] ^ bKey));
            System.out.println(b[i]);
        }

        String str1 = new String(b, "Cp1256");

        b = str1.getBytes("Cp1256");

        System.out.println("Bytes retrieved from str1:");
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i]);
            b[i] = (byte) (b[i] ^ bKey);
        }

        System.out.println("Bytes used to create str2:");
        for (int i = 0; i < b.length; i++) {
            System.out.println(b[i]);
        }

        String str2 = new String(b, "UTF8");
        System.out.println(str2);
    }
}

我得到的输出是:

س
Original bytes from str:
-61
-65
-30
-119
-91
Bytes used to create str1:
-115
-15
-84
-57
-21
Bytes retrieved from str1:
-115
-15
-84
-57
-21
Bytes used to create str2:
-61
-65
-30
-119
-91
س

关于java - Java中utf8字符串及其字节的编码和解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23496995/

相关文章:

string - 在 .htaccess 中重写查询字符串

c - strcpy 和 strcmp 参数的类型不兼容

java - 插入行 SPRING + Hibernate 时的 MySql 编码问题

java - 从包含 utf 8 字符的属性文件中读取

java - 通用列表的 DynamoDBMarshaller

java - 如何以 arrayA 的第一个值乘以数组的最后一个值的方式将两个数组相乘?

java - Java 中的克隆列表

java - ColdFusion 的 RegEx 引擎最近的行为发生变化吗?

ruby-on-rails - 如何在ruby中组合字符串

mysql - 将印度语言数据从 SQL Server 迁移到 MySQL