Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

str_to_hex, hex_to_str in utils.cpp #10

Open
OneMeanDragon opened this issue Mar 8, 2019 · 0 comments
Open

str_to_hex, hex_to_str in utils.cpp #10

OneMeanDragon opened this issue Mar 8, 2019 · 0 comments

Comments

@OneMeanDragon
Copy link

Noticed someone was complaining about str_to_hex and hex_to_str in the file, maybe they'll like this a little better.

void StringToHex(const UCHAR *datainput, UINT32 datalength, std::string &outbuffer)
{
	static const char *values = "0123456789ABCDEF";
	outbuffer = "";
	for (UINT i = 0; i < datalength; i++) {
		const UCHAR c = datainput[i];
		outbuffer += values[c >> 4];
		outbuffer += values[c & 15];
	}
}

void HexToString(const UCHAR *datainput, UINT32 datalength, UCHAR *OutPut)
{
	if (datalength & 1) throw std::invalid_argument("HexToString: Bad length!");
	static const char *values = "0123456789ABCDEF";

	for (UINT i = 0; i < datalength; i += 2)
	{
		char a = datainput[i];
		char b = datainput[i + 1];
		const char* c = std::lower_bound(values, values + 16, a);
		if (*c != a) throw std::invalid_argument("HexToString: [a] not a hex digit");
		const char* d = std::lower_bound(values, values + 16, b);
		if (*d != b) throw std::invalid_argument("HexToString: [b] not a hex digit");

		OutPut[i / 2] = ((c - values) << 4) | (d - values);
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant