`
13146489
  • 浏览: 246828 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

base64中:java与c#的不同

    博客分类:
  • java
 
阅读更多
昨天非常的郁闷的处理这个base64的问题,同样的一个图片文件,在java和c#进行base64编码后结果不一样,让我苦恼很久。

在网上搜索很久,有篇文章提到有可能是如下问题:
byte在java和c#的不同范围的问题:
Java byte : -128 to 127
C# byte : 0 to 255

我经过对比确实确实是这样的。但是后来解决问题后,发现问题根本就没有出在这里。。。
其根本原因在于字符集的问题。

我使用commons-io中的方法读取图片:
FileUtils.readFileToString(new File(path));
查看方法说明才发现,该方法把图片读成uft8的string了。

我后来把方法改为读取到byte[]并且为ascii编码
FileUtils.readFileToByteArray(new File(path));
这样再base64的结果就和C#的一致了。.

综上:这个问题跟java和c#的byte表示范围没有关系。主要你的原始内容(包括字符集)一样,那么结果就一样的。base64算法一般都是一样的,特别情况可能是base64的算法不一样。

我在stackoverflow也发表了个问题。老外也热心的回答了。
http://stackoverflow.com/questions/8518321/base64-difference-between-c-sharp-and-java
老外的回答如下:
You're base64 encoding a string? What do you want that to do? You first need to convert the string to a sequence of bytes, choosing an encoding such as UTF-8 or UTF-16.

My guess is that you managed to use different encodings on both sides. Java's String.GetBytes() uses the default charset (Probably something like Latin1 on western windows versions). For C# you didn't post the relevant code.

To fix this, choose an encoding and use it explicitly on both sides. I recommend using UTF-8.
On the Java side you should use the correct method for encoding, so you don't end up with "modified UTF-8", but since I'm not a java programmer, I don't know which methods output modified UTF-8. I think it only happens if you abuse some internal serialization method.

signed vs. unsigned bytes should not be relevant here. The intermediate byte buffer will be different, but the original string, and the base64 string should be identical on both sides.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics