C++Builder logo
Converting a number to/from an hex/string Conversion de nombre et de string

These little functions convert a number to an hex or to a string and vice versa.  Quatre fonctions pour convertir un nombre en un string ou en hexadécimal et vice versa.

#include <sstream>
#include <string>
#include <exception>

//---------------------------------------------------------------------------
// Convert a number to a string

template<class T>
std::string ToStr(const T &value)
{
  std::ostringstream oss;
  if(!(oss<<std::dec<<value))throw exception("Invalid argument");
  return oss.str();
}


//---------------------------------------------------------------------------
// Convert a string to a number

template<class T>
T ToInt(const std::string &str)
{
  if(str.size()==0)return 0;
  std::istringstream iss(str);
  T result=0;
  if(!(iss>>std::dec>>result))throw exception("Invalid argument");
  return result;
}


//---------------------------------------------------------------------------
// Convert an hex string to a number

template<class T>
T HexToInt(const std::string &str)
{
  if(str.size()==0)return 0;
  std::istringstream iss(str);
  T result=0;
  if(!(iss>>std::hex>>result))throw exception("Invalid argument");
  return result;
}


//---------------------------------------------------------------------------
// Convert a number to an hex string

template<class T>
std::string ToHex(const T &value)
{
  std::ostringstream oss;
  if(!(oss<<std::hex<<value))throw exception("Invalid argument");
  return oss.str();
}