copye char[] to byte[]

J

John A Grandy

How to copy an char[] to a byte[] , where the char[] holds unicode
characters ?
 
G

Guest

public static byte[] CharToByte(char[] c)
{
byte[] b = new byte[c.Length];
for(int i = 0; i < c.Length; i++)
{
b = (byte) c;
}
return b;
}

Simple as that :)
 
L

Lau Lei Cheong

Copied from MSDN:
ms-help://MS.MSDNQTR.2005JUL.1033/cpref/html/frlrfSystemTextEncodingClassGetBytesTopic.htm
ms-help://MS.MSDNQTR.2005JUL.1033/cpref/html/frlrfsystemtextencodingclassgetbytestopic3.htm
Encodes a range of characters from a character array into a byte array.

Supported by the .NET Compact Framework.

[Visual Basic] Overloads Public Overridable Function GetBytes(Char(),
Integer, Integer) As Byte()
[C#] public virtual byte[] GetBytes(char[], int, int);
[C++] public: virtual unsigned char GetBytes(__wchar_t __gc[], int, int)
__gc[];
[JScript] public function GetBytes(Char[], int, int) : Byte[];
-- End of Copy --

If there is error, I suspect you really means
System.Text.Encoding.UTF8.GetBytes().

Spectre said:
I don't beleive you can pass a char[] to that method.

Lau Lei Cheong said:
Use System.Text.Encoding.Unicode.getBytes().

John A Grandy said:
How to copy an char[] to a byte[] , where the char[] holds unicode
characters ?
 
H

Helge Jensen

Spectre said:
public static byte[] CharToByte(char[] c)
{
byte[] b = new byte[c.Length];
for(int i = 0; i < c.Length; i++)
{
b = (byte) c;
}
return b;
}

Simple as that :)


Perhaps OP should have stated that he wated some usable bytes, not just
junk :)

The above code will not convert an array of unicode-char to a
byte-encoding of those same chars in any kind of encoding, unless the
input-character-set is roughly ASCII.

You can select an encoding from System.Text.Encoding and invoke
GetBytes() on that. UTF8 would be a prime candidate.
 
L

Lau Lei Cheong

Yes. Especially considering what people refered to as Unicode means "the
real Unicode", "UTF-7"(this is less likely), "UTF-8" and "UCS-2", with
different size among them, I think it's better to let the Framework routines
handle them for you.
 

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