Java 与 C# 中的 UTF-16 编码 [英] UTF-16 Encoding in Java versus C#

查看:27
本文介绍了Java 与 C# 中的 UTF-16 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取 UTF-16 编码方案中的字符串并对其执行 MD5 散列.但奇怪的是,当我尝试这样做时,Java 和 C# 返回了不同的结果.

I am trying to read a String in UTF-16 encoding scheme and perform MD5 hashing on it. But strangely, Java and C# are returning different results when I try to do it.

以下是Java中的一段代码:

public static void main(String[] args) {
    String str = "preparar mantecado con coca cola";
    try {
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(str.getBytes("UTF-16"));
        byte[] hash = digest.digest();
        String output = "";
        for(byte b: hash){
            output += Integer.toString( ( b & 0xff ) + 0x100, 16).substring( 1 );
        }
        System.out.println(output);
    } catch (Exception e) {

    }
}

输出为:249ece65145dca34ed310445758e5504

以下是C#中的一段代码:

   public static string GetMD5Hash()
        {
            string input = "preparar mantecado con coca cola";
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.Unicode.GetBytes(input);
            bs = x.ComputeHash(bs);
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string output= s.ToString();
            Console.WriteLine(output);
        }

输出为:c04d0f518ba2555977fa1ed7f93ae2b3

我不确定,为什么输出不一样.我们如何更改上面的一段代码,让它们都返回相同的输出?

I am not sure, why the outputs are not the same. How do we change the above piece of code, so that both of them return the same output?

推荐答案

UTF-16 != UTF-16.

UTF-16 != UTF-16.

在 Java 中,getBytes("UTF-16") 返回一个带有可选字节顺序标记的大端表示.C# 的 System.Text.Encoding.Unicode.GetBytes 返回一个 little-endian 表示.我无法从这里检查您的代码,但我认为您需要准确指定转换.

In Java, getBytes("UTF-16") returns an a big-endian representation with optional byte-ordering mark. C#'s System.Text.Encoding.Unicode.GetBytes returns a little-endian representation. I can't check your code from here, but I think you'll need to specify the conversion precisely.

在 Java 版本中尝试 getBytes("UTF-16LE").

Try getBytes("UTF-16LE") in the Java version.

这篇关于Java 与 C# 中的 UTF-16 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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