How do you convert a string to a byte array in .NET?

前端 未结 4 1193
陌清茗
陌清茗 2020-12-08 01:30

I have a string that I need to convert to the equivalent array of bytes in .NET.

This ought to be easy, but I am having a brain cramp.

4条回答
  •  隐瞒了意图╮
    2020-12-08 02:03

    First work out which encoding you want: you need to know a bit about Unicode first.

    Next work out which System.Text.Encoding that corresponds to. My Core .NET refcard describes most of the common ones, and how to get an instance (e.g. by a static property of Encoding or by calling a Encoding.GetEncoding.

    Finally, work out whether you want all the bytes at once (which is the easiest way of working - call Encoding.GetBytes(string) once and you're done) or whether you need to break it into chunks - in which case you'll want to use Encoding.GetEncoder and then encode a bit at a time. The encoder takes care of keeping the state between calls, in case you need to break off half way through a character, for example.

提交回复
热议问题