将byte []转换为String并返回c#

编程入门 行业动态 更新时间:2024-10-20 07:59:08
本文介绍了将byte []转换为String并返回c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用Encoding.Unicode将byte []转换为字符串并返回.有时Encoding.Unicode能够将byte []转换为字符串,有时输出是!=输入.我在做什么错了?

I’m trying to convert a byte[] to a string and back using Encoding.Unicode. Sometimes Encoding.Unicode is able to convert the byte[] to a string and sometimes the output is != the input. What am I doing wrong?

感谢您的帮助.

public static void Main(string[] args) { Random rnd = new Random(); while(true) { Int32 random = rnd.Next(10, 20); Byte[] inBytes = new Byte[random]; for(int i = 0; i < random; i++) inBytes[i] = (Byte)rnd.Next(0, 9); String inBytesString = Encoding.Unicode.GetString(inBytes, 0, inBytes.Length); Byte[] outBytes = Encoding.Unicode.GetBytes(inBytesString); if(inBytes.Length != outBytes.Length) throw new Exception("?"); else { for(int i = 0; i < inBytes.Length; i++) { if(inBytes[i] != outBytes[i]) throw new Exception("?"); } } Console.WriteLine("OK"); } }

推荐答案

您不能为此使用编码:您必须使用类似Convert.ToBase64String/Convert.FromBase64String之类的东西.

You cannot use Encoding for that: you must use something like Convert.ToBase64String / Convert.FromBase64String.

编码假定byte []是根据特定规则进行格式化的,而随机非字符串byte []则不是这种情况.

Encoding assumes the byte[] is formatted according to specific rules, which are not the case for a random non-string byte[].

总结一下:

编码将任意字符串转换为格式化字节[/]或从格式化字节[]

An Encoding turns an arbitrary string to/from a formatted byte[]

Base-64将任意字节[]转换为格式化字符串,或从格式化字符串转换为

Base-64 turns an arbitrary byte[] to/from a formatted string

更多推荐

将byte []转换为String并返回c#

本文发布于:2023-06-08 21:28:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589373.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   byte   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!