C 在位级别读取字符

C 在位级别读取字符,c,binary,bit-manipulation,C,Binary,Bit Manipulation,我希望能够从键盘输入一个字符,并以00000001的格式显示所述键的二进制代码 此外,我还希望以一种允许我输出正确或错误的方式读取位 e、 g 我会发布一个想法,告诉大家我是如何尝试去做的,但我完全不知道,我还在用C做实验,这是我第一次尝试在如此低的级别上编程 谢谢这可能不是最安全的方法-不需要检查卫生/尺寸/类型-但它应该仍然有效 unsigned char myBools[8]; char myChar; // get your character - this is not safe

我希望能够从键盘输入一个字符,并以00000001的格式显示所述键的二进制代码

此外,我还希望以一种允许我输出正确或错误的方式读取位

e、 g

我会发布一个想法,告诉大家我是如何尝试去做的,但我完全不知道,我还在用C做实验,这是我第一次尝试在如此低的级别上编程


谢谢

这可能不是最安全的方法-不需要检查卫生/尺寸/类型-但它应该仍然有效

unsigned char myBools[8];
char myChar;  

// get your character - this is not safe and you should
// use a better method to obtain input...
// cin >> myChar; <- C++
scanf("%c", &myChar);

// binary AND against each bit in the char and then
// cast the result. anything > 0 should resolve to 'true'
// and == 0 to 'false', but you could add a '> 1' check to be sure.
for(int i = 0; i < 8; ++i)
{
   myBools[i] = ( (myChar & (1 << i) > 0) ? 1 : 0 );
}
无符号字符myBools[8];
char-myChar;
//获取你的角色-这不安全,你应该
//使用更好的方法获取输入。。。
//cin>>myChar;0应解析为“true”
//and==0到'false',但您可以添加一个'>1'检查来确保。
对于(int i=0;i<8;++i)
{
myBools[i]=((myChar&(10)?1:0);
}

这将为字符提供一个无符号字符数组(0或1(true或false)。

对于位调整,使用无符号类型通常更安全,因为有符号负值的移位具有与实现相关的影响。普通
字符可以是有符号的,也可以是无符号的(传统上,它在MacIntosh平台上未签名,但在PC上已签名)。因此,首先将字符转换为
unsigned char
类型

然后,您的朋友是位布尔运算符(
&
|
^
~
)和移位运算符(
)。例如,如果您的字符位于变量
x
,则只需使用
((x>>5)&1)即可获得第5位
。移位运算符将值向右移动,删除五个较低的位,并将感兴趣的位移到“最低位置”(也称为“最右边”)。按位and with 1将所有其他位简单地设置为0,因此结果值为0或1,这是您的位。请注意,我从左开始对位进行编号(最右边)到最重要(最左边),我从零开始,而不是一

如果假定字符为8位,则可以将代码编写为:

unsigned char x = (unsigned char)your_character;
int i;

for (i = 7; i >= 0; i --) {
    if (i != 7)
        printf(",");
    printf("%s", ((x >> i) & 1) ? "true" : "false");
}
您可能会注意到,由于I从右到左对位进行编号,但您希望从左到右输出,因此循环索引必须减小

请注意,根据C标准,
unsigned char
至少有8位,但可能有更多位(目前,只有少数嵌入式DSP具有非8位的字符)。为了更加安全,请在代码开头附近添加此项(作为顶级声明):

#包括
#如果字符位!=8
#错误我需要8位字节!
#恩迪夫
如果目标系统恰好是一个特殊的嵌入式DSP,这将阻止成功编译。作为注释上的注释,C标准中的术语“字节”表示“与
无符号字符相对应的基本存储单元”,因此,在C语言中,一个字节可能有八位以上(一个字节并不总是八位字节)。这是一个传统的混淆源。

此代码是C89:

/* we need this to use exit */
#include <stdlib.h>
/* we need this to use CHAR_BIT */
#include <limits.h>
/* we need this to use fgetc and printf */
#include <stdio.h>

int main() {
    /* Declare everything we need */
    int input, index;
    unsigned int mask;
    char inputchar;

    /* an array to store integers telling us the values of the individual bits.
       There are (almost) always 8 bits in a char, but it doesn't hurt to get into
       good habits early, and in C, the sizes of the basic types are different
       on different platforms. CHAR_BIT tells us the number of bits in a byte. 
     */
    int bits[CHAR_BIT];

    /* the simplest way to read a single character is fgetc, but note that
       the user will probably have to press "return", since input is generally 
       buffered */
    input = fgetc(stdin);
    printf("%d\n", input);

    /* Check for errors. In C, we must always check for errors */
    if (input == EOF) {
        printf("No character read\n");
        exit(1);
    }

    /* convert the value read from type int to type char. Not strictly needed,
       we can examine the bits of an int or a char, but here's how it's done. 
     */
    inputchar = input;

    /* the most common way to examine individual bits in a value is to use a 
       "mask" - in this case we have just 1 bit set, the most significant bit
       of a char. */
    mask = 1 << (CHAR_BIT - 1);

    /* this is a loop, index takes each value from 0 to CHAR_BIT-1 in turn,
       and we will read the bits from most significant to least significant. */
    for (index = 0; index < CHAR_BIT; ++index) {
        /* the bitwise-and operator & is how we use the mask.
           "inputchar & mask" will be 0 if the bit corresponding to the mask
           is 0, and non-zero if the bit is 1. ?: is the ternary conditional
           operator, and in C when you use an integer value in a boolean context,
           non-zero values are true. So we're converting any non-zero value to 1. 
         */
        bits[index] = (inputchar & mask) ? 1 : 0;

        /* output what we've done */
        printf("index %d, value %u\n", index, inputchar & mask);

        /* we need a new mask for the next bit */
        mask = mask >> 1;
    }

    /* output each bit as 0 or 1 */
    for (index = 0; index < CHAR_BIT; ++index) {
        printf("%d", bits[index]);
    }
    printf("\n");

    /* output each bit as "true" or "false" */
    for (index = 0; index < CHAR_BIT; ++index) {
        printf(bits[index] ? "true" : "false");
        /* fiddly part - we want a comma between each bit, but not at the end */
        if (index != CHAR_BIT - 1) printf(",");
    }
    printf("\n");
    return 0;
}
/*我们需要这个来使用exit*/
#包括
/*我们需要这个来使用字符位*/
#包括
/*我们需要这个来使用fgetc和printf*/
#包括
int main(){
/*申报我们需要的一切*/
int输入,索引;
无符号整数掩码;
字符输入字符;
/*存储整数的数组,告诉我们各个位的值。
在一个字符中(几乎)总是有8位,但是进入这个字符并没有什么坏处
好习惯早,在C中,基本类型的大小是不同的
在不同的平台上。CHAR_位告诉我们一个字节中的位数。
*/
整数位[字符位];
/*读取单个字符的最简单方法是fgetc,但请注意
用户可能必须按“返回”,因为输入通常是
缓冲*/
输入=fgetc(标准输入);
printf(“%d\n”,输入);
/*检查错误。在C语言中,我们必须始终检查错误*/
如果(输入==EOF){
printf(“未读取字符”);
出口(1);
}
/*将从int类型读取的值转换为char类型。严格来说不需要,
我们可以检查int或char的位,但这里是如何完成的。
*/
inputchar=输入;
/*检查值中单个位的最常用方法是使用
“掩码”-在本例中,我们只设置了1位,即最高有效位
一个字符*/
掩码=1>1;
}
/*将每个位输出为0或1*/
用于(索引=0;索引

你不一定需要三个循环-如果你愿意,你可以把它们组合在一起,如果你只做两种输出中的一种,那么你就不需要数组,你可以在屏蔽它的时候使用每个位值。但是我认为这可以使事情分开,希望更容易理解。

你想在C中还是在C中你放的NET3-5标签将意味着C,但是你也放了一个不一致的C标签。这是一个有趣的练习。应该把括号放在1个编辑范围内,但是你可以检查它,因为我的C没有我的C++那么强大。我认为OP需要任何字符。SCANF应该是代码> SCANF(“%C”,和MyChar);< /C>我认为没有一个叫BooL的类型。在c?+1中,这是一个彻底的例子,它导致我删除了我自己的。任何其他人(除非固执或愚蠢)都应该这样做;)非常彻底,不幸的是,当粘贴到一个空白的源文件中时,我出现了45个错误,大部分是语法错误和未声明的标识符。非常好,效果非常好
#include <limits.h>
#if CHAR_BIT != 8
#error I need 8-bit bytes!
#endif
/* we need this to use exit */
#include <stdlib.h>
/* we need this to use CHAR_BIT */
#include <limits.h>
/* we need this to use fgetc and printf */
#include <stdio.h>

int main() {
    /* Declare everything we need */
    int input, index;
    unsigned int mask;
    char inputchar;

    /* an array to store integers telling us the values of the individual bits.
       There are (almost) always 8 bits in a char, but it doesn't hurt to get into
       good habits early, and in C, the sizes of the basic types are different
       on different platforms. CHAR_BIT tells us the number of bits in a byte. 
     */
    int bits[CHAR_BIT];

    /* the simplest way to read a single character is fgetc, but note that
       the user will probably have to press "return", since input is generally 
       buffered */
    input = fgetc(stdin);
    printf("%d\n", input);

    /* Check for errors. In C, we must always check for errors */
    if (input == EOF) {
        printf("No character read\n");
        exit(1);
    }

    /* convert the value read from type int to type char. Not strictly needed,
       we can examine the bits of an int or a char, but here's how it's done. 
     */
    inputchar = input;

    /* the most common way to examine individual bits in a value is to use a 
       "mask" - in this case we have just 1 bit set, the most significant bit
       of a char. */
    mask = 1 << (CHAR_BIT - 1);

    /* this is a loop, index takes each value from 0 to CHAR_BIT-1 in turn,
       and we will read the bits from most significant to least significant. */
    for (index = 0; index < CHAR_BIT; ++index) {
        /* the bitwise-and operator & is how we use the mask.
           "inputchar & mask" will be 0 if the bit corresponding to the mask
           is 0, and non-zero if the bit is 1. ?: is the ternary conditional
           operator, and in C when you use an integer value in a boolean context,
           non-zero values are true. So we're converting any non-zero value to 1. 
         */
        bits[index] = (inputchar & mask) ? 1 : 0;

        /* output what we've done */
        printf("index %d, value %u\n", index, inputchar & mask);

        /* we need a new mask for the next bit */
        mask = mask >> 1;
    }

    /* output each bit as 0 or 1 */
    for (index = 0; index < CHAR_BIT; ++index) {
        printf("%d", bits[index]);
    }
    printf("\n");

    /* output each bit as "true" or "false" */
    for (index = 0; index < CHAR_BIT; ++index) {
        printf(bits[index] ? "true" : "false");
        /* fiddly part - we want a comma between each bit, but not at the end */
        if (index != CHAR_BIT - 1) printf(",");
    }
    printf("\n");
    return 0;
}