Encoding question

J

JJMM

Hi,

I have a string and I one to convert it to a different encoding, right now I
first convert it to binary and then convert the binary to a string with the
new encoding. That is:
' strText1: Original text
' strText2: text with new enconding (the enconding page number is
intEncodingPage)
Dim bytAux() As Byte = Encoding.Default.GetBytes(strText1)

Dim strText2 as string =
Encoding.GetEncoding(intEncodingPage).GetString(bytAux)

Is there anyway to convert directly without converting to byte first?

Thanks,

jaime
 
M

Mattias Sjögren

I have a string and I one to convert it to a different encoding, right now I
first convert it to binary and then convert the binary to a string with the
new encoding.

That doesn't quite make sense. Whenever you have a String object, its
contents is Unicode (UTF-16 basically). So you're not converting to a
string with a new encoding with your GetString call. What you're doing
is saying that the data in the byte array can be interpreted as
encoded with whatever encoding intEncodingPage represents, and
requests that it's converted to a .NET String. Your current code could
easily result in data loss if the byte array content isn't valid
according to the encoding you're using.

If you want to store the text in a specific encoding and not as a .NET
UTF-16 String, you have to keep in in a byte array. So what you
probably want to do is

Dim encodedText() As Byte =
Encoding.GetEncoding(intEncodingPage).GetBytes(strText1)


Mattias
 

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