Click here to Skip to main content
14,305,260 members
Rate this:
Please Sign up or sign in to vote.
See more:
I am writing a program in C using Visual Studio 2017.

I wrote a function that converts a Hex string to Character. For example "4B" is converted to "K".

The function works but there is a warning message at compile time. I'm wondering if there is a better way to do it.

The warning message:

warning C4477: 'swscanf' : format string '%x' requires an argument of type 'unsigned int *', but variadic argument 1 has type 'LPTSTR'

What I have tried:

void of_hex_to_char(LPTSTR as_hex, LPTSTR as_char)
{
	TCHAR sHex[3];

	memset(sHex, 0x00, sizeof(sHex));

	_tcscpy(sHex, as_hex);
	CharUpper(sHex);

	_stscanf(sHex, L"%x", as_char);

	return;
}
Posted
Updated 22-Jan-19 14:02pm
Comments
Patrice T 21-Jan-19 20:29pm
   
There is no 'swscanf' in this code.
Roland M Smith 21-Jan-19 21:16pm
   
_stscanf is a macro that converts to swscanf.
Rate this:
Please Sign up or sign in to vote.

Solution 1

The error message told you exactly what the problem is. The %x format descriptor for sscanf expects to assign the value to an unsigned integer. You have passed it a pointer to a character string.

An easier option would be to use _tstoul and pass it base 16. That will give you the correct value in binary form.
* as_char = (TCHAR) _tcstoul( as_hex, NULL, 16 );
That will interpret the string passed in as a base 16 value (hexadecimal) and assign it to the location pointed to by as_char. If you print it as a %c you will see its character representation.

_tcstoul has an interesting property - you can pass it a base of zero and it will interpret the string based on a prefix. For hex the string needs to start with 0x and it supports octal strings starting with just the 0.

One minor thing - as_char can be passed as a PCTSTR since it is a constant in this function.
   
v2
Comments
CPallini 22-Jan-19 2:54am
   
5.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Following Rick's suggestion (Note: anyway you have to use an explicit cast in order to suppress the 'narrowing' warning)

TCHAR hex_to_char(LPCTSTR as_hex)
{
	return  (TCHAR)(_tcstoul(as_hex, NULL, 16));
}
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

To avoid changing the calling code, I went with:

void of_hex_to_char(LPTSTR as_hex, LPTSTR as_char)
{
	* as_char = (TCHAR) _tcstoul( as_hex, NULL, 16 );
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100