欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt 将10进制数字与26进制(用A-Z来表示)之间相互转换

程序员文章站 2022-03-14 09:57:51
...

参考:将10进制数字转化为26进制用A-Z来表示

.h文件

#ifndef CONVERSIONOFNUMBERSYSTEM26_H
#define CONVERSIONOFNUMBERSYSTEM26_H

#include <QObject>

class conversionOfNumberSystem26 : public QObject
{
    Q_OBJECT
public:
    explicit conversionOfNumberSystem26(QObject *parent = nullptr);

    static QString ToNumberSystem26(int n);
    static int FromNumberSystem26(QString s);

signals:

};

#endif // CONVERSIONOFNUMBERSYSTEM26_H

.cpp文件

#include "conversionofnumbersystem26.h"

conversionOfNumberSystem26::conversionOfNumberSystem26(QObject *parent) : QObject(parent)
{

}


QString conversionOfNumberSystem26::ToNumberSystem26(int n)
{
    QString s = "";
    while (n > 0)
    {
        int m = n % 26;
        if (m == 0)
        {
            m = 26;
        }
        s = (char)(m + 64) + s;
        n = (n - m) / 26;
    }
    return s;
}

int conversionOfNumberSystem26::FromNumberSystem26(QString s)
{
    if (s.isEmpty())
    {
        return 0;
    }

    int n = 0;
    for (int i = s.length() - 1, j = 1; i >= 0; i--, j *= 26)
    {
        char c = s[i].toUpper().unicode();          //.unicode()是将QChar转为char
        if (c < 'A' || c > 'Z')
        {
            return 0;
        }
        n += ((int)c - 64) * j;
    }
    return n;
}

相关标签: Qt