[ create a new paste ] login | about

Link: http://codepad.org/yfHwXD1h    [ raw code | fork ]

fdfsdfsdfsd - C++, pasted on Jan 23:
/****************************************************************************************
 * Snow
 * File Name: Conversion.cpp
 * Added on: 2009/10/31 06:46:58
 */

/***************************************************************************************/

#include "Snow.h"
#include "Conversion.h"
#include <cstring>

/***************************************************************************************/

/* Converts the given string to an integer. If the string is prefixed by an 'f' it will read the integer
 * as a float, and save it as if the int was a float (it won't convert the float to an integer, though!).
 *
 * If the string is prefixed with '0x' it will accept hexadecimal values too.
 *
 * If you don't want to allow the hex conversion, set allow_hex to false (defaults to true)
 * If you don't want to allow the float conversion, set allow_float to false (defaults to false)
 */

HOT CHECK_RESULT bool ToInt(const string &s, int &out, bool allow_hex, bool allow_float)
{
	char *end;

	union {
		int ret_int;
		float ret_float;
	};

	out = 0;

	if (s.empty())
		return false;

	if (allow_float && s[0] == 'f')
		ret_float = (float)strtod(s.c_str()+1, &end);
	else if (allow_hex && s.size() > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
		ret_int = strtoul(s.c_str()+2, &end, 16);
	else
		ret_int = strtoul(s.c_str(), &end, 10);

	if (*end)
		return false;

	out = ret_int;
	return true;
}

/***************************************************************************************/

#ifdef WINDOWS
#define strtoull _strtoui64
#endif

CHECK_RESULT bool ToUInt64(const string &s, uint64 &out, bool allow_hex)
{
	char *end;

	if (allow_hex && s.size() > 2 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
		out = strtoull(s.c_str()+2, &end, 16);
	else
		out = strtoull(s.c_str(), &end, 10);

	if (*end)
		return false;

	return true;
}

/***************************************************************************************/

CHECK_RESULT bool ToDouble(const string &s, double &out)
{
	char *end;

	out = 0;

	if (s.empty())
		return false;

	out = strtod(s.c_str(), &end);

	if (*end)
		return false;

	return true;
}

/***************************************************************************************/

CHECK_RESULT int ToIntFromHex(const string &hex)
{
	return strtoul(hex.c_str(), NULL, 16);
}

CHECK_RESULT int64 ToInt64FromHex(const string &hex)
{
	return strtoull(hex.c_str(), NULL, 16);
}

/***************************************************************************************/


Create a new paste based on this one


Comments: