Qt 常用的字符转换,QString如何转换成const char类型, 转 PWCHAR wchar_t*

常用的字符转换(日常记录…)

  1. QString如何转换成const char类型
    const char *cmd_data = qstring.toStdString().c_str(); //qstring为待转换的qstring类型字符串
QString format_cmd = u_format_exe_path + " " + mCurrentDisk_name + ":\n\r";
qDebug() << __FUNCTION__ << __LINE__ <<  "format_cmd:" << format_cmd;
const char *cmd_data = format_cmd.toStdString().c_str();
qDebug() << __FUNCTION__ << __LINE__ <<  "cmd_data:" << cmd_data;
  1. QString 转化 PWCHAR wchar_t*
 PWCHAR格式可以看到定义为
 
 typedef WCHAR *PWCHAR,*LPWCH,*PWCH;
 typedef wchar_t WCHAR;
  
 PWCHAR实际上就是 wchar_t* 
  
  • 方法一
    测试过可用
QString spi_path = filepath;
PWCHAR strSpiPath=new wchar_t[MAX_PATH];  //#define MAX_PATH 260  MAX_PATH是在minwindef.h中定义的
int s1=spi_path.toWCharArray(strSpiPath);
strSpiPath[s1]=0;

其中toWCharArray
QString::toWCharArray(wchar_t * array)
QT官方文档确实注明了:Note: This function does not append a null character to the array.

qstring.h
toWCharArray的返回值,我的理解貌似是字符串strSpiPath的长度的值,然后strSpiPath[s1]=0;是把最后一个位置设成0,类似于字符串拷贝到字符数组里面,要在其后面添加一个\0标识符似的。

qstring.h

inline int QString::toWCharArray(wchar_t *array) const
{
    if (sizeof(wchar_t) == sizeof(QChar)) {
        memcpy(array, d->data(), sizeof(QChar) * size());
        return size();
    } else {
        return toUcs4_helper(d->data(), size(), reinterpret_cast<uint *>(array));
    }
}

相对应的wchar类型的转换为qstring,用这个fromWCharArray

  • 方法二
    未测试过,贴出来供参考
PWCHAR strSpiPath;
QString spi_path = filepath;
qDebug()<< __FILE__ << __FUNCTION__ << __LINE__ << "spi_path:" << spi_path;
wchar_t *spi_path_w_char= const_cast<wchar_t *>(spi_path.toStdWString().c_str());
strSpiPath = spi_path_w_char;

//wchar_t 转Qstring
QString str_test= QString::fromWCharArray(strSpiPath);
  1. UCHAR 如何转换成QString 类型

QString u_sn = QString::fromUtf8(reinterpret_cast(sn_buf), 16);

        UCHAR sn_buf[32];
        memset(sn_buf,0x0,sizeof (sn_buf));
        int ret_sn =   GetSN( hDev, sn_buf,  16);
        QString u_sn;
        if(ret_sn == 1)
        {
            QString u_sn = QString::fromUtf8(reinterpret_cast<char *>(sn_buf), 16);
        }
        else
        {
            u_sn.clear();
        }

十进制转十六进制qstring

            QString xor_str_hex = QString("%1").arg(xor_int, 2, 16, QChar('0'));  // 保留2位,转换为16进制,不足补0

你可能感兴趣的:(string,Qt,Creator,笔记,qt,qstring,字符串)