|
|
发表于 2025-11-9 15:15:59
|
显示全部楼层
安徽省滁州市
#include <iostream>
#include <iomanip>
#include <chrono>
#include <vector>
#include <cstring>
#include <ctime>
// 通用类型转字节集
template <typename T>
std::vector<unsigned char> to_bytes(const T& value) {
std::vector<unsigned char> bytes(sizeof(T));
std::memcpy(bytes.data(), &value, sizeof(T));
return bytes;
}
// 打印字节集(十六进制)
void print_bytes(const std::vector<unsigned char>& bytes) {
std::cout << "字节集内容(十六进制):";
for (unsigned char b : bytes) {
std::cout << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(b) << " ";
}
std::cout << std::dec << std::endl;
}
// 将时间戳格式化为中文年月日(带星期)
std::string format_chinese_date(std::time_t time) {
std::tm* time_info = std::localtime(&time);
if (!time_info) {
return "时间格式转换失败";
}
// 手动映射星期(避免依赖系统locale)
const char* weekdays[] = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
int wday = time_info->tm_wday; // 0=周日,6=周六
const char* weekday_str = (wday >= 0 && wday < 7) ? weekdays[wday] : "未知";
// 格式化年月日
char buffer[100];
std::strftime(buffer, sizeof(buffer), "%Y年%m月%d日 ", time_info);
return std::string(buffer) + weekday_str;
}
int main() {
// 1. 获取原始时间戳
auto now = std::chrono::system_clock::now();
std::time_t original_time = std::chrono::system_clock::to_time_t(now);
// 输出中文年月日
std::string chinese_date = format_chinese_date(original_time);
std::cout << "原始时间戳(秒数):" << original_time << " → 中文日期:"
<< chinese_date << std::endl;
// 2. 转换为64位整数(无精度损失,推荐)
uint64_t time_as_uint64 = static_cast<uint64_t>(original_time);
std::cout << "转换为uint64_t后的值:" << time_as_uint64 << std::endl;
// 3. 转为字节集
std::vector<unsigned char> bytes = to_bytes(time_as_uint64);
print_bytes(bytes);
// 4. 从字节集读回
uint64_t read_back_uint64;
std::memcpy(&read_back_uint64, bytes.data(), sizeof(uint64_t));
std::time_t recovered_time = static_cast<std::time_t>(read_back_uint64);
std::cout << "从字节集读回的uint64_t:" << read_back_uint64
<< " → 转回时间戳:" << recovered_time << std::endl;
// 验证恢复的时间是否正确(中文格式)
std::string recovered_chinese_date = format_chinese_date(recovered_time);
std::cout << "恢复的中文日期:" << recovered_chinese_date << std::endl;
// 5. 验证是否一致
if (recovered_time == original_time) {
std::cout << "✅ 转换成功!前后时间戳一致" << std::endl;
} else {
std::cout << "❌ 转换失败!前后时间戳不一致" << std::endl;
}
return 0;
}
|
评分
-
| 参与人数 2 | 好评 +1 |
荣誉 +1 |
收起
理由
|
笨潴
| |
+ 1 |
热心帮助他人,荣誉+1,希望继续努力(*^__^*) 嘻嘻! |
96692
| + 1 |
|
欢迎常来帮助新人,谢谢~ |
查看全部评分
|