SQLite Forum

To and From Hex Conversion Methods
Login
I have using your function compiled by CYGWIN, however the isxdigit crashes program. I modified the code so that it solves this problem, and also adds bigendian option.

```c
/*
** given a hex string converts it to int
*/
static void hex2intFunc(sqlite3_context* context, int argc, sqlite3_value** argv)
{
	const char* src;
	uint64_t value = 0;
	uint64_t nextChar = 0;
	int nShift = 0;
	assert(argc == 2);
	if (SQLITE_NULL == sqlite3_value_type(argv[0]))
	{
		sqlite3_result_null(context);
		return;
	}
	bool bBigEndian = sqlite3_value_int64(argv[1]);
	//if ( bBigEndian & ~0x1UL)
	//{
	//	sqlite3_result_error(context, "The second argument should be 0 (little endian) or 1 (big endian)", -1);
	//	return;
	//}

	if (sqlite3_value_type(argv[0]) == SQLITE_TEXT)
	{
		src = (char*)sqlite3_value_text(argv[0]);
		if (strlen(src) > 16)
		{
			// sqlite3_result_int64(context, (sqlite_int64)value);
			return;
		}
		while (*src != 0)
		{
			switch (src[0])
			{
			case 'A'...'F':
				nextChar |= (uint64_t)src[0] - 'A' + 0x0A;
				break;
			case 'a'...'f':
				nextChar |= (uint64_t)src[0] - 'a' + 0x0A;
				break;
			case '0'...'9':
				nextChar |= (uint64_t)src[0] - '0';
				break;
			default:
				nextChar = 0x100;
			}
			if (nextChar & 0x100)
			{
				value = 0;
				nextChar = 0;
				break;
			}
			if (bBigEndian)
			{
				nShift++;
				if (!(nShift & 0x01))
				{
					nextChar <<= ((nShift - 2)<<2);
					value |= nextChar;
					nextChar = 0;
				}
				else
					nextChar <<= 4;
			}
			else
			{
				value = value << 4;
				value |= nextChar;
				nextChar = 0;
			}
			sqliteNextChar(src);
		}
		if (nextChar)
		{
			nextChar <<= ((nShift -1) << 2);
			value |= nextChar;
		}
		sqlite3_result_int64(context, (sqlite_int64)value);
		// break;
	}
}
```