3

I am working on C#, trying below code

byte[] buffer = new byte[str.Length];
buffer = Encoding.UTF8.GetBytes(str);

In str I've got lengthy data but I've got problem in getting complete encoded bytes. Please tell me what's going wrong and how can I overcome this problem?

2
  • 1
    Nothing is probably "goin wrong" here. I believe you will have to clearify your question. What is it that you believe is wrong and what did you expect. Commented Nov 13, 2009 at 16:14
  • thanks for reply... I got complete encoded when i cal for the first time...but when it is called for the second time getting problem...Is ther any restriction on length of the "str" used to get bytes...bcoz str i am using contain lengthy string data Commented Nov 13, 2009 at 16:18

3 Answers 3

6

Why are you creating a new byte array and then ignoring it? The value of buffer before the call to GetBytes is being replaced with a reference to a new byte array returned by GetBytes.

However, you shouldn't expect the UTF-8 encoded version of a string to be the same length in bytes as the original string's length in characters, unless it's all ASCII. Any character over U+007F takes up at least 2 bytes.

What's the bigger picture here? What are you trying to achieve, and why does the length of the byte array matter to you?

Sign up to request clarification or add additional context in comments.

Comments

3

The proper use is:

 byte[] buffer = Encoding.UTF8.GetBytes(str);

Comments

1

In general, you should not make any assumptions about length/size/count when working with encoding, bytes and chars/strings. Let the Encoding objects do their work and then query the resulting objects for that info.

Having said that, I don't believe there is an inherent length restriction for the encoding classes. I have several production apps doing the same work in the opposite direction (bytes encoded to chars) which are processing byte arrays in the 10s of megabytes.

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.