C# String to Byte Array

By gilbitron in C# on 27/03/2009 at 01:38

Views: 4511
Tagged: c#, conversion

Starter:

Converts a String to a Byte Array and vice versa.

Main Course:

//String to byte array
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] byteArray =  enc.GetBytes(str);
 
//Byte array to string
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
String str = enc.GetString(byteArr);
 

Expand Report Code | Install Coda Clip

Please log in to vote.

Compliments to the Chef

  1. Comment by Dave on 27/03/2009 at 12:17

    You are aware that a string IS a char array, right?

    byte charVal = (byte)("Hello, World!")[0];

  2. Comment by Ben Bishop on 11/09/2009 at 09:23

    Although this works for some strings, note that it only works with strings made from 7bit ASCII characters (0-127).

    I'm looking for a "better" solution that just allows me to look at the byte encoding of the string without go through text encoding transformations.

  3. Comment by Johhny Quest on 06/07/2010 at 06:28

    Another unreadable piece of shit webpage.

How was your Meal?


  • Allowed HTML: <b><strong><u><i><em><a>

  • Why ask? It helps us stop spam comments.