0

简单的问题:我想在文件中写入当前日期。以下是我的代码:

void fileWR::write()
{
QFile myfile("date.dat");
if (myfile.exists("date.dat"))
myfile.remove();

myfile.open(QIODevice::ReadWrite);
QDataStream out(&myfile);
out << (quint8) QDate::currentDate().day();     // OK!!
out << (quint8) QDate::currentDate().month();   // OK!!
out << (quint8) QDate::currentDate().year();    // NOT OK !!!

myfile.close();
}

当我阅读文件时,我发现一个字节代表日期(0x18 代表 24 日),一个字节代表月份(0x02 代表 2 月)和一个错误字节代表年份(0xe6 代表 2022 年)。我需要一年的最后两个数字(例如:2022 -> 22)。我能怎么做?谢谢保罗

4

1 回答 1

1

十六进制的 2022 是 0x7E6 ,当您保存将其转换为 uint8 时,最高有效位将被截断以获得您所指示的内容。想法是使用模块运算符将 2022 转换为 22,然后保存:

QDataStream out(&myfile);
QDate now = QDate::currentDate();
out << (quint8) now.day();
out << (quint8) now.month();
out << (quint8) (now.year() % 100);
于 2022-02-24T15:14:55.057 回答