StringBuilder到字节数组 [英] StringBuilder to byte array

查看:139
本文介绍了StringBuilder到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将StringBuilder转换为字节数组的最简单方法是什么?

谢谢

解决方案

嗯,你应该只是从StringBuilder创建一个字符串(调用

ToString),然后你可以使用BinaryFormatter序列化它,或者调用

静态公开的Unicode编码实例上的GetBytes方法

Encoding类上的Unicode属性返回字节。


后一种选择可能更容易。前者被提到

只是为了表明有多种方法可以做到这一点。

-

- Nicholas Paldino [.NET / C# MVP]

- mv*@spam.guard.caspershouse.com


" Peter" < pc ***** @ nospam.nospamwrote in message

news:ui ************** @ TK2MSFTNGP06.phx.gbl ...


将StringBuilder转换为字节数组的最简单方法是什么?


谢谢



嗯,你需要选择一个编码...最简单的方法是

(在这里使用UTF8):

byte [] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());


制作它需要多复杂取决于场景。


Marc


Marc,


我不知道我会选择UTF8,但我会使用Unicode

编码。似乎(我可能在这里错了)OP只需要构成字符串的

字节,并且Unicode编码实例是最可靠的
弹性方式做到这一点(假设可读性不是因素,并且存储空间的两倍是成本。)

-

- Nicholas Paldino [.NET / C#MVP]

- mv*@spam.guard.caspershouse.com


" Marc Gravell" < ma ********** @ gmail.comwrote in message

news:d2 ******************** ************** @ y5g2000h sf.googlegroups.com ...


嗯,你需要选择一个编码...最简单的方法是

(在这里使用UTF8):

byte [] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString( ));


你需要多大的复杂程度取决于场景。


Marc



What is the easiest way to convert StringBuilder to byte array?
Thanks

解决方案

Well, you should just create a string from the StringBuilder (calling
ToString) and then you can serialize that using the BinaryFormatter, or call
the GetBytes method on the Unicode Encoding instance exposed by the static
Unicode property on the Encoding class to return the bytes.

The latter option is more than likely easier. The former was mentioned
just to show that there are multiple ways to do it.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Peter" <pc*****@nospam.nospamwrote in message
news:ui**************@TK2MSFTNGP06.phx.gbl...

What is the easiest way to convert StringBuilder to byte array?
Thanks



Well, you''ll need to pick an encoding... the simplest way is then
(using UTF8 here):
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());

How complex you need to make it depends on the scenario.

Marc


Marc,

I don''t know that I would pick UTF8, but rather, I''d use the Unicode
encoding. It seems (and I could be wrong here) that the OP just wants the
bytes that make up the string, and the Unicode Encoding instance is the most
resiliant way of doing that (assuming readability isn''t a factor, and at a
cost of twice the storage space).
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Marc Gravell" <ma**********@gmail.comwrote in message
news:d2**********************************@y5g2000h sf.googlegroups.com...

Well, you''ll need to pick an encoding... the simplest way is then
(using UTF8 here):
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());

How complex you need to make it depends on the scenario.

Marc



这篇关于StringBuilder到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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