Add sanity checks for input string in wxHexToDec()

Check if the length of the string is appropriate and if it contains hexadecimal characters.
Also document this function.

Closes #12814.
This commit is contained in:
Artur Wieczorek
2017-02-23 20:07:04 +01:00
parent 2ecd4a07ba
commit 71305cff62
3 changed files with 35 additions and 4 deletions

View File

@@ -296,15 +296,23 @@ inline int wxHexToDec(const char* buf)
if (buf[0] >= 'A')
firstDigit = buf[0] - 'A' + 10;
else
else if (buf[0] >= '0')
firstDigit = buf[0] - '0';
else
firstDigit = -1;
wxCHECK_MSG( firstDigit >= 0 && firstDigit <= 15, -1, wxS("Invalid argument") );
if (buf[1] >= 'A')
secondDigit = buf[1] - 'A' + 10;
else
else if (buf[1] >= '0')
secondDigit = buf[1] - '0';
else
secondDigit = -1;
return (firstDigit & 0xF) * 16 + (secondDigit & 0xF );
wxCHECK_MSG( secondDigit >= 0 && secondDigit <= 15, -1, wxS("Invalid argument") );
return firstDigit * 16 + secondDigit;
}

View File

@@ -1474,4 +1474,25 @@ wxString wxDecToHex(unsigned char dec);
@header{wx/utils.h}
*/
void wxDecToHex(unsigned char dec, char* ch1, char* ch2);
/**
Convert 2-character hexadecimal string to decimal integer.
@param buf
String containing uppercase hexadecimal characters, not prefixed
by @c 0x. Its length must be at least 2 characters. If it is longer
than 2 characters, only first two will be converted to the number.
@return
An integer number between 0 and 255 that is equivalent to the number
in @a buf, or @c -1 if @a buf is not a hexadecimal string.
@header{wx/utils.h}
*/
int wxHexToDec(const wxString& buf);
/**
@overload
*/
int wxHexToDec(const char* buf);
//@}

View File

@@ -122,10 +122,12 @@ static const char hexArray[] = "0123456789ABCDEF";
// Convert 2-digit hex number to decimal
int wxHexToDec(const wxString& str)
{
wxCHECK_MSG( str.Length() >= 2, -1, wxS("Invalid argument") );
char buf[2];
buf[0] = str.GetChar(0);
buf[1] = str.GetChar(1);
return wxHexToDec((const char*) buf);
return wxHexToDec(buf);
}
// Convert decimal integer to 2-character hex string (not prefixed by 0x).