RadaD
RadaD

Reputation: 85

QString to qint16

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.

Upvotes: 1

Views: 611

Answers (2)

kzsnyk
kzsnyk

Reputation: 2211

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.

Upvotes: 1

Farshid616
Farshid616

Reputation: 1484

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.

Upvotes: 1

Related Questions