ByteUtil.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #ifndef _UTILS_TIME_BYTE_UTIL_H_
  2. #define _UTILS_TIME_BYTE_UTIL_H_
  3. #include <string>
  4. #include <iostream>
  5. #include <sstream>
  6. /**
  7. * @brief 字节操作类
  8. */
  9. class ByteUtil {
  10. public:
  11. static void copyUnsignedCharArray(unsigned char* source, unsigned char destination[], size_t size) {
  12. std::copy(source, source + size, destination);
  13. }
  14. static void copyUnsignedCharArray(unsigned char* source, unsigned char* destination, size_t size, size_t& offset) {
  15. // 确保不超出目标数组的界限
  16. size_t remainingSize = offset + size > 1024 ? 1024 - offset : size;
  17. if (remainingSize > 0) {
  18. std::copy(source, source + remainingSize, destination + offset);
  19. offset += remainingSize; // 更新偏移量
  20. }
  21. }
  22. // std::string byteToString(const unsigned char* bytes, unsigned long int length) {
  23. // return std::string(reinterpret_cast<const char*>(bytes), length);
  24. // }
  25. static std::string byteToString(const unsigned char* data, size_t size) {
  26. std::string result;
  27. // 将每个 unsigned char 转换为 char 并添加到结果字符串中
  28. for (size_t i = 0; i < size; ++i) {
  29. result += static_cast<char>(data[i]);
  30. }
  31. return result;
  32. }
  33. static std::string convertToString(const unsigned char* data, size_t size) {
  34. std::string dataStr = "";
  35. for (int i = 0; i < size; ++i) {
  36. char buf[1024];
  37. sprintf(buf, "%02x", data[i]);
  38. dataStr += buf;
  39. }
  40. return dataStr;
  41. }
  42. static unsigned char stringToByte(const std::string& str) {
  43. std::stringstream ss;
  44. ss << std::hex << str;
  45. unsigned int intValue;
  46. ss >> intValue;
  47. return static_cast<unsigned char>(intValue);
  48. }
  49. static std::string timestampToHex(int timestamp) {
  50. std::stringstream ss;
  51. ss << std::hex << timestamp;
  52. return ss.str();
  53. }
  54. static std::string timestampToHex(time_t timestamp) {
  55. std::stringstream ss;
  56. ss << std::hex << timestamp;
  57. return ss.str();
  58. }
  59. };
  60. #endif /* _UTILS_TIME_BYTE_UTIL_H_ */