String To Byte array

D

Dan C

Is there a routine in c# that will transform a string ie"Hello Mom" into a
Byte[] array. I have found
char[] cTmp = pString.ToCharArray();

But I have not been able to figure out how to convert a char into a hex
value and place that value into the byte[].

Thanks for your help

Dan C
 
J

Joshua Flanagan

Look at the Encoding classes. They have a GetBytes method that will do
exactly what you are looking for.
I think they are under System.Text.Encoding.
 
R

Romain TAILLANDIER

i use that, it's seems to work...

string a = "hello mom";
byte b = new byte[a.length];

foreach (char c in a.ToCharArray())
b[i++] = Convert.ToByte(c);

to back to a string, i use that:

//suppose i have
byte[] b;

char[] a = new char[b.length];
int i=0;
foreach (byte c in b)
a[i++] = Convert.ToChar(c);

string str = new string(a);


hope that help.
ROM
 
J

Jon Skeet [C# MVP]

Romain TAILLANDIER said:
i use that, it's seems to work...

string a = "hello mom";
byte b = new byte[a.length];

foreach (char c in a.ToCharArray())
b[i++] = Convert.ToByte(c);

That will break as soon as you get any characters with Unicode values
over 255. Use System.Text.Encoding.GetBytes - that's what it's there
for.
 
R

Romain TAILLANDIER

hey hey, hi jon ...

thank you for this remark, i will change my code ... :s
ROM




Jon Skeet said:
Romain TAILLANDIER said:
i use that, it's seems to work...

string a = "hello mom";
byte b = new byte[a.length];

foreach (char c in a.ToCharArray())
b[i++] = Convert.ToByte(c);

That will break as soon as you get any characters with Unicode values
over 255. Use System.Text.Encoding.GetBytes - that's what it's there
for.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top