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

懵懂的女人 提交于 2019-12-06 03:36:18

From ctype.h:

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

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

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.

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