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

烈酒焚心 提交于 2019-12-10 10:13:40

问题


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.


回答1:


From ctype.h:

#define isascii(c)  ((c & ~0x7F) == 0)



回答2:


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);



回答3:


(inchar & MASK) == MASK

you are testing if the masked pattern equals to initial mask. And the mask is 0x80. This will be true if you have a non-ascii char.




回答4:


The MASK you want to use is 0x80.
That being said you might want to consider using ctype.h to make your checks: http://linux.die.net/man/3/isascii

BTW, ascii when including the extended ascii codes is 8 bits otherwise it is 7 bits, but not all of those are printable characters.

Also inChar should be of type int to hold the return value of getchar(). Its not valid to call printf expecting a char and giving it an int. You should cast it to char first to get the types correct.




回答5:


Not that this question isn't already well answered, but i wanted to add that you could use a bit shift operation.

bool is_printable( char c )
{
    return !( c & (1 << 7) );
}


来源:https://stackoverflow.com/questions/9234886/check-if-a-char-is-ascii-using-bitmasks-and-bit-operators-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!