Encoding question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • JJMM

    #1

    Encoding question

    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.Defaul t.GetBytes(strT ext1)

    Dim strText2 as string =
    Encoding.GetEnc oding(intEncodi ngPage).GetStri ng(bytAux)

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

    Thanks,

    jaime







  • Mattias Sjögren

    #2
    Re: Encoding question

    >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.GetEnc oding(intEncodi ngPage).GetByte s(strText1)


    Mattias

    --
    Mattias Sjögren [C# MVP] mattias @ mvps.org
    http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
    Please reply only to the newsgroup.

    Comment

    Working...