QString to qint16

Viewed 151

I am trying to convert a QString to a qint16 with

udpListenPort = ui->lineEdit_UdpListenPort->text().toShort();

but it converts "40690" to 0.

I tried different casts and conversions but neither works. I think I can't see the wood for the trees here.

2 Answers

The maximal value a qint16 (which is a typedef short qint16; /* 16 bit signed */) can hold is 32767 using two's complement, hence "40690" overflows and signed integer overflow is undefined behaviour.

Use quint16 instead (which is a typedef unsigned short quint16; /* 16 bit unsigned */) and ushort QString::toUShort(bool *ok = nullptr, int base = 10) const.

You came most of the way, just change the toShort() to toUShort() to fix that.

udpListenPort = ui->lineEdit_UdpListenPort->text().toUShort();

quint16 is just a typedef for unsigned short.

Related