Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
3.82/5 (4 votes)
See more:
What is the best way to convert char[] to byte[] in C# 2010?

Please note that we do not know in advance the format of a single char. It can either be ASCII or Unicode or UTF-8 or UTF-16.

Is there one universal conversion to overcome this?

And what is the vice versa conversion in this case, say to Unicode?
Posted
Updated 23-Aug-12 2:58am
v2
Comments
Manfred Rudolf Bihy 23-Aug-12 9:30am    
What is C# 2010? There is no such thing! .NET has version numbers as in 1.1, 2.0, 3.0, 3.5, 4.0 etc.

There are more solutions.
The first is:
C#
byte[] byteArray = Encoding.yourEncoding.GetBytes(charArray1);

More information about this method:
http://msdn.microsoft.com/en-us/library/5881c0k9.aspx[^]

The second is:
C#
byte[] byteArray = Convert.FromBase64CharArray(charArray1,0,charArray1.Length);

More information about this method: http://msdn.microsoft.com/en-us/library/system.convert.frombase64chararray.aspx[^]


Hope this helps.
 
Share this answer
 
Comments
Vitaly Tomilov 23-Aug-12 12:32pm    
For the third time, I have no information about the type of encoding the array has. Anyway, the issue has been resolved. Cheers!
Thomas Daniels 23-Aug-12 12:38pm    
You can try all encodings, and then
you'll see what's the best.
 
Share this answer
 
Comments
Vitaly Tomilov 23-Aug-12 11:02am    
That approach works only if you know the type of encoding, which I don't, as I clearly stated. I decided to re-post the problem that I'm having closer to what it actually is: CLOB: char[] serialization
Turns out I didn't need it after all. I was trying to serialize char[] via a string, for which I could simply call:

Serialization:

- Convert char[] to String using String(char[]) constructor;

De-serialization:

- Call String.ToCharArray();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900