我怎样才能安全地转换为字节数组转换为字符串并回? [英] How can I safely convert a byte array into a string and back?

查看:89
本文介绍了我怎样才能安全地转换为字节数组转换为字符串并回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不关心的编码和东西,只要我回去完全一样的字节数组。

I don't really care about encoding and stuff, as long as I get back the exact same byte array.

所以,总结一下:我如何转换成一个字节数组转换为字符串,然后该字符串返回到相同的字节数组,我开始以

So to sum up: How do I convert a byte array into a string, and then that string back into the same byte array I started with?

推荐答案

要字节转换为字符串和背部的绝对最安全的方法是使用BASE64:

The absolute safest way to convert bytes to a string and back is to use base64:

string base64 = Convert.ToBase64String(bytes);
byte[] bytes = Convert.FromBase64String(base64);

你保证不要让无效UNI code序列,如代理对上半年无下半年的方式。没有什么是要决定将数据正常化到一些奇怪的事情(这是所有ASCII)。有没有使用未在注册的Uni code,或类似的东西code点的机会。哦,你可以剪切和粘贴没有太多的恐惧了。

That way you're guaranteed not to get "invalid" unicode sequences such as the first half of a surrogate pair without the second half. Nothing's going to decide to normalize the data into something strange (it's all ASCII). There's no chance of using code points which aren't registered in Unicode, or anything like that. Oh, and you can cut and paste without much fear, too.

是的,你结束了4个字符,每3个字节 - 但是这是一个很小的代价为您的数据不会被破坏知识

Yes, you end up with 4 characters for every 3 bytes - but that's a small price to pay for the knowledge that your data won't be corrupted.

这篇关于我怎样才能安全地转换为字节数组转换为字符串并回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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