我对C很陌生,所以对它了解不多。指针是我还没有学到的东西...... 我需要以十进制和二进制显示单个字符。用小数表示很简单,但我无法以任何方式将其转换为二进制...我得到 ASCII 码并将其模块与 2 进行比较,但它显示的数字非常尴尬...代码有什么问题?(它在葡萄牙语 这是我的代码:
#include <stdio.h>
#include <conio.c> //library my professor created to assist his students
#include <string.h>
#define MAXIMO 8
int main( void )
{
char caracter;
int aux, resto[MAXIMO], contador, decimal, numero;
printf( "Digite um UNICO caracter: " );
caracter = getch();
numero = caracter;
decimal = caracter;
aux = 0;
do
{
if (numero % 2 == 0)
{
resto[aux] = 0;
}
else
{
resto[aux] = 1;
}
numero = numero / 2;
aux++;
}
while (numero >= '0');
//system("cls");
printf( "\n\n%d\n\n", aux );
printf( "\nCaracter em Binario: " );
for (contador = aux; contador >= 0; contador--)
{
printf( "%d", resto[contador] );
}
printf( "\nValor decimal do caracter: %d", decimal );
getch();
return 0;
}
我用的东西比如 getch();并返回 0;最后只是为了让我的老师不要杀了我……我不完全知道为什么它在那里,但它必须在那里。
最佳答案
您的代码在 while
条件中有一些错误:
#include <stdio.h>
#include <string.h>
#define MAXIMO 8
int main( void )
{
char caracter;
int aux, resto[MAXIMO], contador, decimal, numero;
printf( "Digite um UNICO caracter: " );
caracter = getchar(); // I used getchar instead of getch()
numero = caracter;
decimal = caracter;
aux = 0;
do
{
if (numero % 2 == 0)
{
resto[aux] = 0;
}
else
{
resto[aux] = 1;
}
numero = numero / 2;
aux++;
}
while (numero > 0); // > than 0 not >= '0'
//system("cls");
printf( "\n\n%d\n\n", aux );
printf( "\nCaracter em Binario: " );
for (contador = aux-1; contador >= 0; contador--) //aux-1
{
printf( "%d", resto[contador] );
}
printf( "\nValor decimal do caracter: %d", decimal );
getchar();
return 0;
}
注意
- '0' 和 0 不同
>
(大于)和>=
(大于或等于)有不同的含义
关于c - 需要帮助从 ASCII 转换为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40007330/