添加项目文件。

This commit is contained in:
ldh
2026-11-06 14:45:09 +08:00
parent fb76f2ed7d
commit 24cbecc2cc
3437 changed files with 895900 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
#ifndef BYTECONVERTER_H
#define BYTECONVERTER_H
#include <iostream>
#include <vector>
#include <type_traits>
#include <cstring>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <string>
class ByteConverter {
public:
static uint32_t bswap32(uint32_t v) {
return ((v & 0x000000FFu) << 24) |
((v & 0x0000FF00u) << 8) |
((v & 0x00FF0000u) >> 8) |
((v & 0xFF000000u) >> 24);
}
template<typename T>
static T fromLittleEndian(const uint8_t* data, size_t offset = 0) {
T value = 0;
for (size_t i = 0; i < sizeof(T); ++i) {
value |= static_cast<T>(data[offset + i]) << (i * 8);
}
return value;
}
template<typename T>
static T convert(const std::vector<uint8_t>& data, size_t offset = 0, bool is_little_endian = true) {
if (data.size() < offset + sizeof(T)) {
throw std::runtime_error("Data buffer overflow");
}
T value;
memcpy(&value, data.data() + offset, sizeof(T));
if (is_little_endian) {
return value; // 假设当前平台是小端序
} else {
// 大端序转小端序(根据平台实现)
if (sizeof(T) == 4) {
uint32_t v32 = 0;
std::memcpy(&v32, &value, sizeof(uint32_t));
v32 = bswap32(v32);
std::memcpy(&value, &v32, sizeof(uint32_t));
return value;
}
// 其他类型处理...
}
return value;
}
// 字符串解析(增强版)
static std::string convert_str(
const std::vector<uint8_t>& data,
size_t offset = 0,
size_t max_length = SIZE_MAX,
bool trim_leading_null = true,
bool trim_trailing_null = true
);
private:
static void validate_size(const std::vector<uint8_t>& data, size_t offset, size_t required);
};
#endif // BYTECONVERTER_H