Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. QML and Qt Quick
  4. How to convert QString to unsigned char in Qt
Forum Update on Monday, May 27th 2025

How to convert QString to unsigned char in Qt

Scheduled Pinned Locked Moved Unsolved QML and Qt Quick
2 Posts 2 Posters 1.0k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P Offline
    P Offline
    Praveen.Illa
    wrote on last edited by Praveen.Illa
    #1

    Hi Team,
    I am new to Qt and am trying to understand Qt conversions (like QString to unsigned char, QString to unisgned short, etc..)

    I have a C code like below

    unsigned short us = -1;
    printf("us = %d\n", us);
    

    The output is 65535 which is as expected (the data type range roll over happens here).

    Same thing, I have tried with Qt i.e., converting QString to unsigned char or unsigned short like below

    QString str = "-1";
    qDebug() << "value = " << str.toUShort();
    

    The output is 0.

    How can I get the output as 65535 in Qt ?

    DiracsbracketD 1 Reply Last reply
    0
    • P Praveen.Illa

      Hi Team,
      I am new to Qt and am trying to understand Qt conversions (like QString to unsigned char, QString to unisgned short, etc..)

      I have a C code like below

      unsigned short us = -1;
      printf("us = %d\n", us);
      

      The output is 65535 which is as expected (the data type range roll over happens here).

      Same thing, I have tried with Qt i.e., converting QString to unsigned char or unsigned short like below

      QString str = "-1";
      qDebug() << "value = " << str.toUShort();
      

      The output is 0.

      How can I get the output as 65535 in Qt ?

      DiracsbracketD Offline
      DiracsbracketD Offline
      Diracsbracket
      wrote on last edited by Diracsbracket
      #2

      @Praveen-Illa said in How to convert QString to unsigned char in Qt:

      QString str = "-1";

      toUshort() fails with negative number strings (if you use the ok argument, it will indeed return false), so you need to convert to a signed int as an intermediate step first and cast it afterwards:

          QString str = "-1";
          bool OK;
          ushort val = str.toInt(&OK);
          qDebug() << val << OK;
      
      1 Reply Last reply
      2

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved