Skip to content

Instantly share code, notes, and snippets.

@vladimirgamalyan
Last active September 28, 2021 04:29
Show Gist options
  • Save vladimirgamalyan/74200b1e09573ee37245 to your computer and use it in GitHub Desktop.
Save vladimirgamalyan/74200b1e09573ee37245 to your computer and use it in GitHub Desktop.
Make std::string hex representation of array
#pragma once
#include <sstream>
#include <iomanip>
#include <vector>
class HexString
{
public:
HexString& hexArray()
{
return hex().fill('0').delimiter(", ").prefix("0x").postfix("").start("[ ").finish(" ]");
}
HexString& hex()
{
hex_ = true;
return *this;
}
HexString& dec()
{
hex_ = false;
return *this;
}
HexString& delimiter(const std::string& v)
{
delimiter_ = v;
return *this;
}
HexString& prefix(const std::string& v)
{
prefix_ = v;
return *this;
}
HexString& postfix(const std::string& v)
{
postfix_ = v;
return *this;
}
HexString& uppercase()
{
uppercase_ = true;
return *this;
}
HexString& lowecase()
{
uppercase_ = false;
return *this;
}
HexString& fill(char v)
{
fill_ = v;
return *this;
}
HexString& start(const std::string& v)
{
start_ = v;
return *this;
}
HexString& finish(const std::string& v)
{
finish_ = v;
return *this;
}
std::string str(const void* data, size_t len) const
{
const unsigned char* d = reinterpret_cast<const unsigned char*>(data);
std::stringstream ss;
ss << start_;
ss << std::setfill(fill_);
if (hex_)
ss << std::hex;
if (uppercase_)
ss << std::uppercase;
for (size_t i = 0; i < len; ++i)
{
if (i)
ss << delimiter_;
ss << prefix_ << std::setw(2) << static_cast<int>(d[i]) << postfix_;
}
ss << finish_;
return ss.str();
}
std::string str(const std::vector<unsigned char>& data) const
{
return str(data.data(), data.size());
}
private:
bool uppercase_ = false;
bool hex_ = false;
char fill_ = '0';
std::string delimiter_;
std::string prefix_;
std::string postfix_;
std::string start_;
std::string finish_;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment