2

How do you convert string to byte[] in C#?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
n3wb13
  • 21
  • 3
  • 3
    Keep in mind that the array of bytes you get is entirely dependent upon the string encoding which is being used -- the textual representation of a string is lost if you do not how how it is encoded. – void-pointer Apr 14 '11 at 00:17

3 Answers3

6

Note that .NET strings are encoded as Unicode (UTF-16):

byte[] bytes = Encoding.Unicode.GetBytes("a string");
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
6

using byte[] data = Encoding.UTF8.GetBytes(myString);

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • 2
    Yep but I've actually never came close to using any UTF16 specific characters to date and UTF8.GetBytes always did the job (especially when performance is critical) – Teoman Soygul Apr 14 '11 at 00:20
  • I know but I was assuming that the OP wanted the actual bytes that the string contains. – Mark Cidade Apr 14 '11 at 00:26
0

You can use LINQ:

var input     = "myValue";
var byteInput = input.ToCharArray ().Select ( character => ( byte ) character ).ToArray ();

Assert.AreEqual ( input, new string ( byteInput.Select ( character => ( char ) character ).ToArray () ) );

And add the encoding before or after if encoding is something you want to do.

Janus
  • 125
  • 1
  • 8