String To Byte array

  • Thread starter Thread starter Dan C
  • Start date Start date
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
 
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.
 
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
 
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.
 
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.
 
Back
Top