0

Been doing quite a lot of work with Qt and it just hit me, which one should I use to convert my QStrings to QByteArray and back? And there is some other issues where I dont know what to do exactly.

For example when dealing with QUrl. I have an object where on of the members are a QString and I'm setting it like this:

blobByType->setBlobAbsoluteUri(request.url().toEncoded()); 

The toEncoded() converts it to utf8 and and all non-ASCII characters are then percent encode. When I then set the QString to a QByteArray it automatically converts it Ascii.

Also, when doing most of my converting from QString to QByteArray I currently use toUtf8().

My question is, what should I use when converting from QString to QByteArray and vice versa?

5
  • You don't say what you intend to use this QByteArray for, or what kind of strings you intend to store in it. Commented Apr 17, 2012 at 1:01
  • the qbytearray is needed when dealing with some libraries and some functions that wants a char array. using QString Commented Apr 17, 2012 at 1:07
  • OK, then what do those libraries and functions accept? Do they expect UTF-8, or do they only take ASCII? Or do they take something else entirely, like Latin-1 and such? Commented Apr 17, 2012 at 1:07
  • actaully have no idea to be honest. im using utf8 for the base64 encoding lib atm and the key that im generating seems to work Commented Apr 17, 2012 at 1:22
  • 1
    Base64 uses ASCII. Granted, any ASCII string is also UTF8, so it doesn't really matter. Commented Apr 17, 2012 at 2:10

2 Answers 2

3

UTF-8 and ASCII are usually exactly the same thing when dealing with English characters. The difference is that if you ever use non-English characters UTF-8 will be able to support it while ASCII won't. I suggest using UTF-8 just to play it safe.

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

3 Comments

how to make QString use fromUtf8() when creating string?
newString = QString::fromUtf8(yourArray);? I don't really understand what you're asking...
qt-project.org/doc/qt-4.8/qstring.html#QString-9 currently use the constructor which converts it to ascii
1

If there is a chance that you are going to use non-english characters it's better to use UTF-8. It's standard and good practice to use it because you never know who might be reusing your code in the future.

3 Comments

so should i change how QString() converts QBYteArray?
I'm not QT expert. You wrote, you were using toUtf8() doing conversion. I understand you already use UTF8. So my piece of advice is keep doing it.
If you're worried about implicit conversions, I'd suggest to define QT_NO_CAST_FROM_ASCII and QT_NO_CAST_TO_ASCII to disable them alltogether. And then use toUtf8/fromUtf8,QLatin1String() etc. to explicitely convert.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.