Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a char is ASCII using Bitmasks and Bit Operators in C

I need to write program that will check each individual char from stdin to see if it is an ASCII character. I know that what it needs to check is if the 8th bit (7th in code, if I remember correctly) is a 0, since ASCII only uses 7 bits, but I'm having difficulty figuring out just how exactly to make it check the specific bit. This is what I have at time of writing.

#include <stdio.h>

#define MASK 7

int     main(void)
{

auto    char    inChar;

    do
    {
    inChar = getchar();

    // Breaks the do-while loop if it detects End of File
    if (inChar == EOF)
        {
        break;
        }

    printf("%c", inChar);

    if ( inChar == (0 & MASK))
        {
        printf("Not an ASCII Character.\n");
        }

    }while(1);

    puts("\n");

    return 0;
}

I am aware that I don't have the coder properly implemented to check every character value yet, but I will worry about that later. Right now I just need help with getting it to check that specific bit in the variable.

Also this is my first time asking here so please forgive any improper formatting of my question.

like image 725
user1202963 Avatar asked Oct 21 '25 06:10

user1202963


2 Answers

From ctype.h:

#define isascii(c)  ((c & ~0x7F) == 0)
like image 113
jfs Avatar answered Oct 23 '25 23:10

jfs


You want the seventh bit, not the value 7.

/* 10000000 = 2^7 = 128 */

uint8_t b;
printf("Leftmost bit is %d\n", (b & 128) != 0);
like image 43
cnicutar Avatar answered Oct 23 '25 22:10

cnicutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!