Convert String to Byte Array

Figured this might come in handy for someone (or at least for me later on when I go looking for it). Below is a simple method for converting a given string to an array of bytes. Wouldn't be nice if you could just do something like this: Return myString.ToByteArray()? The String class already has ToCharArray, why not ToByteArray?

VB.NET
Imports System.Text 

Public Shared Function ConvertStringToByteArray(ByVal stringToConvert As String) As Byte()

    Return (New UnicodeEncoding).GetBytes(stringToConvert)

End Function

 

C#

using System.Text;

 

public static byte[] ConvertStringToByteArray(string stringToConvert)

{

    return (new UnicodeEncoding()).GetBytes(stringToConvert);

}

 

Print | posted on Friday, November 12, 2004 11:06 AM

Feedback

# re: Convert String to Byte Array

left by Curt at 12/7/2004 3:49 PM
This helped me. Thanks!

# re: Convert String to Byte Array

left by abocz at 12/10/2004 7:42 AM
Me too. Thanks!

# re: Convert String to Byte Array

left by aspnet at 12/14/2004 1:54 PM
me too :)

# re: Convert String to Byte Array

left by leonard at 12/28/2004 7:43 PM
thx !

# re: Convert String to Byte Array

left by Shreesha at 1/4/2005 2:06 AM
Phew....this was of great helpfor which I was fighting for a week !!!
Thanx a lot!!!

# re: Convert String to Byte Array

left by WANA at 1/10/2005 6:09 AM
GREAT THX

# re: Convert String to Byte Array

left by Johnny Xie at 1/24/2005 8:15 AM
Thanks a million.

# re: Convert String to Byte Array

left by Tahir at 1/27/2005 1:32 AM
excallent function

# re: Convert String to Byte Array

left by Tahir at 1/27/2005 1:32 AM
excallent function

# re: Convert String to Byte Array

left by Doug Ross at 1/28/2005 4:27 AM
Thanks, simple though elegant. You have saved me a lot of time looking for the right classes to use to do this.... cheers

# re: Convert String to Byte Array

left by Pradnya at 1/31/2005 10:52 PM
That was really helpful. Thanks!

# re: Convert String to Byte Array

left by walid at 2/2/2005 6:41 AM
thanks this help me!!

# re: Convert String to Byte Array

left by Derek at 2/2/2005 10:46 PM
You're my hero. I'm a bit of a newb... so it took me a few seconds to find th that UnicodeEncoding means System.Text.UnicodeEncoding

Thanks for this!

# This really Helped me

left by Ashiks at 2/3/2005 10:42 PM
Thanx a lot !!!!!!!!! the FileWriter and Convert Classes were fooling me and now i have this so i am master of program again

# re: Convert String to Byte Array

left by Mathias at 2/10/2005 4:40 AM
If anyone is experiencing that this code only converts the first char in your string use this instead:

string test = "byte test";
byte[] toSend = System.Text.Encoding.ASCII.GetBytes(test.ToCharArray());

# re: Convert String to Byte Array

left by Dave at 2/10/2005 5:27 AM
Mathias: All testing I did on my code converted the whole string, not just the first character. Not sure why you experienced something different.

# re: Convert String to Byte Array

left by Gyler at 2/17/2005 9:05 AM
Me three!

# re: Convert String to Byte Array

left by Wolfledge at 2/25/2005 2:53 PM
I has found that the ToCharArray returned a UNICODE while I was processing ASCII text files, and within my search I found this, and with a small tweak I was good to go.

public static byte[] ConvertStringToByteArray(string stringToConvert)

{

return (new ASCIIEncoding()).GetBytes(stringToConvert);

}

Thank you for this post!!

# re: Convert String to Byte Array

left by atmchuck at 3/4/2005 2:35 AM
You helped me, too! Thanks.

# re: Convert String to Byte Array

left by Michael at 3/15/2005 4:58 AM
Great! I need this!!!
Thank you very much!

# re: Convert String to Byte Array

left by Bo Hansen at 3/17/2005 2:23 AM
Yes this is indeed a very great post. It is a simple opperation and EXTREMLY handy then working with embedded systems as my self. The "tweak" from Wolfledge (2/25/2005 2:53 PM), makes the function evenmore handy. The orginal method is splitting a char (16-bit) into bytearrays. For every char there is two bytes. The first 8-bit and the second 8-bit. The tweak from Wolfledge returns a exact byte array of the incomming byte. (Supposing that your stringToConvert does NOT contain anything above 8-bit).
Very need .... Thanx alot

# re: Convert String to Byte Array

left by rAjEEsh at 3/30/2005 1:59 AM
cool... thanks :-)

# re: Convert String to Byte Array

left by NtOrZor at 4/5/2005 12:45 PM
Thank you so much for this elegant solution! It is exactly what I was looking for. I was close to writing my own function before I found this. Thanks!

# re: Convert String to Byte Array

left by Ben at 4/18/2005 6:45 PM
I love you!

# re: Convert String to Byte Array

left by Dave at 4/18/2005 7:04 PM
Ben: Um... I love you, too... I guess... I mean, I'm not exactly sure how to respond... just glad I could help ;-)

# re: Convert String to Byte Array

left by jeff at 4/18/2005 11:35 PM
its great, short and sweet =)

# re: Convert String to Byte Array

left by Shawn at 5/7/2005 6:58 PM

This was an awesome answer to a nightmare I was having. I altered it to output UTF-16 ...

Return (New System.Text.UnicodeEncoding).BigEndianUnicode.GetBytes(stringToConvert)

Thanks for posting this. You can't imagine how much time this saved me!

# re: Convert String to Byte Array

left by Ali at 5/20/2005 10:26 AM
Excellent. Vary useful. :-)

# re: Convert String to Byte Array

left by Johan Nilsson at 5/21/2005 7:12 AM
Greetings from Sweden! Thank you!

# re: Convert String to Byte Array

left by Tushar Parekh at 5/27/2005 8:03 AM
Thanks .. This really helped me. Thanks again !!!

# re: Convert String to Byte Array

left by StuFF at 5/31/2005 8:13 AM
Wow.... Since december it seems you helped a bunch of people... If you had received 1 $ for each one you'd be rich ;) Thanks. you also helped me ! Freakin stoOpid that there is nothing like ToByteArray(); !

# re: Convert String to Byte Array

left by Marc at 6/1/2005 10:59 PM
Anyone knows how to convert byte arrays to strings ?

# re: Convert String to Byte Array

left by Petr at 6/15/2005 1:25 PM
To convert byte arrays to strings use System.BitConverter.ToString method

# re: Convert String to Byte Array

left by LaDan at 6/15/2005 10:56 PM
How can one covert string to byte array in C++

# re: Convert String to Byte Array

left by João Nóbrega at 6/16/2005 8:10 AM
Thank you

# re: Convert String to Byte Array

left by vik at 6/24/2005 6:06 PM
Helped me too
Thanks

# re: Convert String to Byte Array

left by Pete at 7/1/2005 7:30 AM
Helped me a lot. Thanks.

# re: Convert String to Byte Array

left by Stan at 7/6/2005 1:37 AM
That was really helpful!
thanx a lot

# re: Convert String to Byte Array

left by Wayne at 7/8/2005 1:13 AM
Great bit of code found it on google after bit of searching.

# re: Convert String to Byte Array

left by Trevor at 7/8/2005 9:46 AM
it's so fashionable to say thanks here that I'm going to say it too!

# re: Convert String to Byte Array

left by Norman at 7/9/2005 5:11 PM
This was exactly what I was lookin' for.

# re: Convert String to Byte Array

left by Wei at 7/10/2005 11:45 AM
Man! It's amazing how simple thing like this can helps a great deal.
Truely thanks!!

# Convert String from Byte Array

left by Usman Rauf at 7/12/2005 12:20 AM
To retrieve a string from converted byte array, use similar approach.

private string ConvertByteArrayToString(byte[] bt)
{
return (new System.Text.UnicodeEncoding()).GetString(bt);
}

# re: Convert String to Byte Array

left by MP09 at 7/15/2005 6:15 AM
Great!

# re: Convert String to Byte Array

left by someguy51 at 7/18/2005 3:26 PM
Thanks a lot!

# re: Convert String to Byte Array

left by Vikas Goyal at 7/18/2005 10:58 PM
Thank you very much for the code, as this is very good

# re: Convert String to Byte Array

left by Sun_moon at 7/22/2005 7:47 PM
It dosn't work well all the time.

# re: Convert String to Byte Array

left by Japan at 7/22/2005 7:48 PM
It dosn't work well all the time.

# re: Convert String to Byte Array

left by iSMAIL at 7/27/2005 1:22 AM
hOW DO YOU COVERT A STRING OF BYTES TO AN ARRAY OF BYTES

# re: Convert String to Byte Array

left by Martin at 8/4/2005 11:54 PM
NICE!
Got me one problem: it only converted about 2000 chars of the string. Change the UnicodeEncoding to ASCIIEncoding, then it'll work better. Or, it worked better for me that way, that is.
/Martin

# re: Convert String to Byte Array

left by Kismet at 8/6/2005 6:40 PM
why not avoid the whole 'new' keyword, and go with something like:

C#
----
string theString = "testing";
byte[] byteArray = Encoding.Unicode.GetBytes(theString);
theString = Encoding.Unicode.GetString(byteArray);

there's also Encoding.ASCII.GetByte()/GetString()
and so much more.

# re: Convert String to Byte Array

left by Art at 8/6/2005 9:15 PM
ITs sad when Google returns a better answer to a conversion function than the same query does to the microsoft online help in the IDE. I can't believe they make a mystery out of such a simple thing to do.

Thanks again

# re: Convert String to Byte Array

left by alexei at 8/12/2005 1:45 PM
Hey, thanks a lot :)

# re: Convert String to Byte Array

left by sam at 8/15/2005 1:39 PM
Thanks a million. This is fantastic !

Cheers

# re: Convert String to Byte Array

left by rc at 8/31/2005 2:58 AM
Very useful

# re: Convert String to Byte Array

left by Sarim at 9/1/2005 5:55 AM
Ponka

# re: Convert String to Byte Array

left by chris at 9/11/2005 6:49 PM
Awesome... just what I was looing for :D

# re: Convert String to Byte Array

left by Andy Green at 9/28/2005 6:41 AM
You are the MAN - and probably will be for years to come - as geeks everywhere, for the next several years, google for just this thing :-)

# re: Convert String to Byte Array

left by Joe at 10/27/2005 5:08 AM
Would you marry my daughter?

# re: Convert String to Byte Array

left by ullas at 11/7/2005 3:25 AM
thanks, it helped me also. Also please tell me how to convert these bytes back to string

# re: Convert String to Byte Array

left by ullas at 11/7/2005 3:35 AM
thanks...i got it....
UnicodeEncoding()).GetString( byteArray );

# re: Convert String to Byte Array

left by Rajeev at 11/9/2005 6:17 PM
Me too. Kind of silly that you cannot do String.ToByteArray(). I chanced upon Encoding.GetBytes() but now I don't know which Encoding to use, ie. how do I find out what the encoding of the given string is.

# re: Convert String to Byte Array

left by Dusha at 12/5/2005 10:18 AM
Cool!!! Thanks a lot!!!

# re: Convert String to Byte Array

left by landrian at 12/14/2005 10:43 AM
When I see your solution I erase the function that I created

private static byte[] GetBytes(string s)
{
int C = s.Length;
byte[] arr = new byte[C];
for (int i=0; i<C; i++)
arr[i] = (byte)s[i];
return arr;
}

And use

System.Text.ASCIIEncoding cod = new System.Text.ASCIIEncoding();
byte[] arr = cod.GetBytes(s);

But then I see in the reflector that the code of the ASCIIEncoding is the same, and with more conditionals, so I test both solutions and the function is a lot faster than the ASCIIEncoding or UnicodeEncoding. In resume not always the code that already exists is better than your own code.

# re: Convert String to Byte Array

left by Frankie goes to hollywood at 12/16/2005 11:59 AM
Thanks baby! That was just what I needed.

# re: Convert String to Byte Array

left by Ram at 12/30/2005 2:11 AM
Thanks dude.. it saved my precious time on weekend :)

# re: Convert String to Byte Array

left by Dampee at 1/8/2006 5:40 AM
Super! Thanks!

# re: Convert String to Byte Array

left by Yossi at 1/9/2006 4:59 AM
Another one!

# re: Convert String to Byte Array

left by Abel Aghorighor at 1/18/2006 7:24 AM
Thanks YOU are great

# re: Convert String to Byte Array

left by simon at 1/25/2006 1:27 AM
thanks

# re: Convert String to Byte Array

left by Guy at 1/30/2006 9:39 AM
Anyone noticed that Encoding.ASCII.GetBytes helpfully strips all your characters to 7 bit?

So when using extended chars such as ä or ö they get misrepresented.

Anyone know how to get the full 8-bit ASCII into a byte array?

# re: Convert String to Byte Array

left by Daniel Michaeloff at 2/3/2006 5:32 PM
I just ran into this problem myself. If you're being kinky reading binary data as strings and want the actual bytes, you need to construct the StreamReader using System.Text.Encoding.Default, and extract the bytes using the same:

byte[] binaryBytes = System.Text.Encoding.Default.GetBytes(stringOfRawBinary);

# re: Convert String to Byte Array

left by KVH at 2/13/2006 11:51 PM
Thanks :)

# re: Convert String to Byte Array

left by Martin at 2/22/2006 2:58 AM
Thanks to you all. Had been having issues getting a pdf file from Microsoft access and writing it out as a binary stream. Turns out Access encodes the data as Unicode. Needed to convert this to 8-bit binary. The following worked well ..

'store the raw data from Access memo field (unicode encoded binary)
Dim BlobData() As Byte = RawData
' convert to unicode string
Dim Mystring As String = Encoding.Unicode.GetString(BlobData)
' convert from unicode string to 8-bit binary data
BlobData = System.Text.Encoding.Default.GetBytes(Mystring)

# re: Convert String to Byte Array

left by bob at 2/27/2006 1:51 PM
you just saved me a lot of time!
Here are BASE 64 encoders for those of you who work with web forms:

string Encr(string strVal)
{ byte[] binVal = (new UnicodeEncoding()).GetBytes(strVal);
return Convert.ToBase64String(binVal);
}

string Decr (string strVal)
{ byte[] binVal = Convert.FromBase64String(strVal);
return (new UnicodeEncoding()).GetString(binVal);
}

# re: Convert String to Byte Array

left by Dan Hixon at 3/3/2006 10:23 AM
Gracias!

# re: Convert String to Byte Array

left by Programmer at 3/7/2006 11:43 AM
Thanks!

# re: Convert String to Byte Array

left by anjee at 3/8/2006 3:49 PM
Thank you very much, saved me a lot of time.

# re: Convert String to Byte Array

left by Jay at 3/9/2006 6:40 AM
Sweet code, thanks

# Caveat on Encoding.Default

left by Daniel Michaeloff at 3/13/2006 1:42 PM
The only issue with Encoding.Default is that it attempts to interpret the first few bytes of the file as an encoding, and uses no encoding only if it doesn't recognize them.

So, be careful with arbitrary binary data.

# Convert BYTE Array To String

left by Rajesh at 3/20/2006 5:07 AM
I want conversion of Byte array to string.

# re: Convert String to Byte Array

left by RockSRQ at 3/30/2006 1:20 PM
any luck with a PDF file stored in a foxpro memo field?

It's coming out but not complete.....

ideas?? I've tried all of the encoding options to no avail...

# re: Convert String to Byte Array

left by JD at 4/4/2006 8:06 AM
Your method is too slow. For a super fast conversion try this (safe and unsafe versions provided, both faster than using the encoder.)

static private byte[] ToByteArray(string source)
{
byte[] dest = new byte[source.Length];

#if UNSAFE
//Slightly faster than safe version
//Much faster than System.Text..GetBytes()
unsafe
{
fixed(char* c = source)
{
for (int i = 0; i < dest.Length; i++)
{
dest[i] = (byte)*(c + i);
//dest[i] = (byte)source[i];
}
}
}
#else
for (int i = 0; i < dest.Length; i++)
{
dest[i] = (byte)source[i];
}
#endif

return dest;
}

# re: Convert String to Byte Array

left by net guest at 4/16/2006 10:47 PM
great,thx!

# re: Convert String to Byte Array

left by Pablo at 4/17/2006 1:46 AM
Where where you last time i needed this??? LOL thank this is very helpfull...i cant belive i didnt think last time :( O well i have it now and you cant have it back :)-

# re: Convert String to Byte Array

left by txic brain at 4/19/2006 12:34 AM
ur sweet.. this helped me a lot

# re: Convert String to Byte Array

left by Ivan Yeh at 4/26/2006 4:23 AM
really thank you!

# re: Convert String to Byte Array

left by cj at 4/27/2006 10:25 AM
converting to byte array is the same to get the ascii from the string?

# re: Convert String to Byte Array

left by Oleksiy at 5/1/2006 6:30 AM
It's really helpful!
Comments have been closed on this topic.