将Hex转换为带符号的Dec

时间:2013-10-03 08:57:39

标签: c++ qt number-formatting qtcore

我有问题,将十六进制值转换为带符号的Dec值。事情是我不知道该怎么做。我正在使用Qt,这是示例代码。

#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int x=0xA92B;
    qDebug()<<x;
    return a.exec();
}

现在我得到43307,但我想得到-22229。有办法吗?

2 个答案:

答案 0 :(得分:5)

请尝试使用short x = 0xA92B;,因为如果您使用int,则会将0xA92B存储为无符号数字。

答案 1 :(得分:0)

我不确定你为什么需要这个,但看到不同的Qt'ish方式和“短”低于它们的结果。不幸的是,我认为你需要做空。

的main.cpp

#include <QString>
#include <QTextStream>
#include <QDebug>

int main()
{
    int x = 0xA92B;
    short shortX = 0xA92B;
    QString hexString = QString::number(0xA92B);
    QTextStream decTextStream(&hexString);
    int d;
    decTextStream >> d;

    qDebug() << shortX;
    qDebug() << hexString.toInt();
    qDebug() << d;

    return 0;
} 

建筑物(类似的东西)

g++ -fPIC -I/usr/include/qt -I/usr/include/qt/QtCore -lQt5Core main.cpp && ./a.out

输出

-22229
43307
43307