C library - iswxdigit() function



The C wctype library iswxdigit() function is used to check whether a given wide character (represented by wint_t) corresponds (if narrowed) to a hexadecimal numeric character, i.e. one of the "0123456789ABCDEF".

This function can be useful for input validation, parsing hexadecimal digit, data sanitization, or syntax highlighting.

The "iswdigit" and "iswxdigit" are the only two standard wide-character functions that are unaffected by the currently installed C locale.

Syntax

Following is the C library syntax of iswxdigit() function −

int iswxdigit( wint_t ch )

Parameters

This function accepts a single parameter −

  • ch − It is a wide character of type 'wint_t' to be checked.

Return Value

This function returns Non-zero value if the wide character is a hexadecimal numeric character, zero otherwise.

Example 1

The following is the basic c example that demonstrate the use of iswxdigit() function.

#include <wctype.h>
#include <stddef.h>
#include <wchar.h>
int main()
{
   wchar_t ch = L'F';
   if (iswxdigit(ch)) {
      // The character is a valid hexadecimal digit (0-9, a-f, A-F)
      wprintf(L"%lc is a valid hexadecimal digit.\n", ch);
   } else {
      wprintf(L"%lc is not a valid hexadecimal digit.\n", ch);
   }
}

Output

Following is the output −

F is a valid hexadecimal digit.

Example 2

We create a c program and using the iswxdigit() to check whether the hexadecimal numeric character is valid or not.

#include <wctype.h>
#include <stddef.h>
#include <wchar.h>
int main()
{
   const wchar_t *hexString = L"3A4f";
   while (*hexString) {
      if (!iswxdigit(*hexString)) {
         wprintf(L"Invalid hexadecimal string.\n");
         return 1;
      }
      hexString++;
   }
   wprintf(L"Valid hexadecimal string.\n");
}

Output

Following is the output −

Valid hexadecimal string.

Example 3

Let's create another c program to filter out non-hexadecimal characters from user input or data streams.

#include <wctype.h>
#include <stddef.h>
#include <wchar.h>
int main() {
   const wchar_t *input = L"123GHI456";
   wchar_t sanitized[100];
   int j = 0;
   
   for (int i = 0; input[i] != L'\0'; i++) {
     if (iswxdigit(input[i])) {
       sanitized[j++] = input[i];
     }
   }
   sanitized[j] = L'\0';
   wprintf(L"Sanitized hexadecimal string: %ls\n", sanitized);
}

Output

Following is the output −

Sanitized hexadecimal string: 123456
c_library_wctype_h.htm
Advertisements