使用C中的位掩码和位运算符检查字符是否为ASCII [英] Check if a char is ASCII using Bitmasks and Bit Operators in C

查看:361
本文介绍了使用C中的位掩码和位运算符检查字符是否为ASCII的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写程序,它将检查每个单独的char从stdin,看看它是否是一个ASCII字符。我知道它需要检查是如果第8位(代码中的第7,如果我记得正确)是一个0,因为ASCII只使用7位,但我很难弄清楚如何确切地使它检查特定位。这是我在撰写本文时。

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.

推荐答案

ctype.h

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

这篇关于使用C中的位掩码和位运算符检查字符是否为ASCII的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆