carraysascii

Check if array is ASCII


How do I check in C if an array of uint8 contains only ASCII elements? If possible please refer me to the condition that checks if an element is ASCII or not


Solution

  • Your array elements are uint8, so must be in the range 0-255

    For standard ASCII character set, bytes 0-127 are used, so you can use a for loop to iterate through the array, checking if each element is <= 127.

    If you're treating the array as a string, be aware of the 0 byte (null character), which marks the end of the string

    From your example comment, this could be implemented like this:

    int checkAscii (uint8 *array) {
        for (int i=0; i<LEN; i++) {
            if (array[i] > 127) return 0;
        }
        return 1;
    }
    

    It breaks out early at the first element greater than 127.