Click here to Skip to main content
15,849,829 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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:

C++
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 15: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.

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.
C++
* 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.
 
Share this answer
 
v2
Comments
CPallini 22-Jan-19 2:54am    
5.
Following Rick's suggestion (Note: anyway you have to use an explicit cast in order to suppress the 'narrowing' warning)

C
TCHAR hex_to_char(LPCTSTR as_hex)
{
	return  (TCHAR)(_tcstoul(as_hex, NULL, 16));
}
 
Share this answer
 
v2
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 );
}
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900