Files
energy_storage/src/common/Utils.h
2025-09-04 19:31:04 +08:00

120 lines
2.8 KiB
C++

#ifndef _Utils_H_
#define _Utils_H_
#include <vector>
#include <string>
#include <sstream>
#include <string.h>
#include <iomanip>
#include <functional>
#include <thread>
//#include "Crypto.h"
using namespace std;
class Utils
{
public:
static string toStr(int v);
static string toStr(float v, int precision = 2);
static string toStr(double v, int precision = 2);
static int toInt(const std::string& str);
static float toFloat(const string& str);
static double toDouble(const string& str);
static int64_t hexbinToInt(const string& str, bool swap = false);
static int hexstrToInt(const string& str);
static string from_hex_text(string s);
static string to_hex_text(string s, string d = " ");
template<typename T>
static void append_bytes(vector<unsigned char>& dest, const T& src, int len)
{
int start = static_cast<int>(dest.size());
dest.resize(start + len);
memcpy_s(&dest[start], len, &src, len);
}
// 获取当前时间的时间戳(毫秒)
static int64_t time(std::string s="");
// 获取当前时间的格式字符串
static string timeStr(int64_t ts=0, std::string fmt = "%Y-%m-%d %H:%M:%S");
// 获取当前日期的时间戳(毫秒)
static int64_t date();
// 获取当前日期的格式字符串
static string dateStr(int64_t ts = 0, std::string fmt = "%Y-%m-%d %H:%M:%S");
static string timeStrMS(std::string fmt = "%Y-%m-%d %H:%M:%S");
//static string timeStr(int64_t ts, std::string fmt = "%Y-%m-%d %H:%M:%S");
//static int64_t time(string dt="", int zone = 0);
//static string time_to_string(int64_t dt, std::string fmt="%Y-%m-%d %H:%M:%S");
//static bool time_string_to_tm(string dt, std::tm& t);
std::string duration_str(int64_t t)
{
auto h = t / 3600;
auto m = (t % 3600) / 60;
auto s = (t % 3600) % 60;
std::string str = std::to_string(s) + "";
if (m > 0 || h > 0)
{
str = std::to_string(m) + "" + str;
}
if (h > 0)
{
str = std::to_string(h) + "小时" + str;
}
return str;
}
static unsigned short crc16(unsigned char* data, unsigned int len);
static string Utils::gbkToUtf8(string s);
static string Utils::utf8ToGbk(string s);
static void sleep_ms(int ms);
static int random(int min, int max);
static void split(string buf, string c, vector<string>& res);
static std::string readFile(std::string filename);
static std::string toHexStr(int64_t val);
};
class TimeTick
{
public:
int64_t tickMS_ = 0;
TimeTick(int t=0)
{
if (t !=0) { tickMS_ = Utils::time(); }
}
bool elapse(int64_t ms, bool reset = true)
{
auto tick_now = Utils::time();
bool res = tick_now - tickMS_ > ms;
if (res && reset)
{
tickMS_ = tick_now;
}
return res;
}
void reset()
{
tickMS_ = Utils::time();
}
};
#endif // !!! _Utils_H_