0

I'm porting a Java function as below codes to C#, it converts a char array to UTF-8 format, and then convert to byte array, how can do this in .Net platform via C#?

Java code:

public static byte[] GetBytes(char[] chars) 
{
    Charset cs = Charset.forName("UTF-8");
    CharBuffer cb = CharBuffer.allocate(chars.length);
    cb.put(chars);
    cb.flip();
    ByteBuffer bb = cs.encode(cb);
    byte[] array = bb.array();

    return array
}

2 Answers 2

2
byte[] array = System.Text.Encoding.UTF8.GetBytes(new string(chars));
Sign up to request clarification or add additional context in comments.

Comments

2

Please, have a look at class System.Text.Encoding. It has plenty of methods and static members to work with encoding.

Encoding.UTF8.GetBytes("Some string"); Encoding.UTF8.GetBytes(charArray);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.