【发布时间】:2015-10-16 05:07:32
【问题描述】:
我需要编写一个程序来读取字符串并打印出该字符串的二进制 ASCII 码。我不知道字符串的长度,我需要在程序的某个地方实现数据结构。我写的源代码是:
#include <stdio.h>
int dec_to_binary(int c, int d);
//initialize data structure for binary value
struct binary{
int value;
};
struct word{
int w_value;
};
int main(){
char wordd[256];
printf("Input a string of characters (no spaces): \n");
//scanf("%s", w);
fgets(wordd, sizeof(wordd), stdin);
printf("You typed: %s", wordd);
int size_word = sizeof(wordd);
struct word w[size_word]; //stores character string
struct binary b[size_word]; //initizalize corresponding binary array for char string inputted by user
int i = 0;
int char_int = 0;
for (i = 0; i < size_word; i++)
{
char_int = w[i].w_value;
b[i].value = dec_to_binary(char_int, size_word); //stores binary value in binary struct array
}
printf("The binary ASCII code for this string is: %d", b);
return 0;
}
int dec_to_binary(int c, int d)
{
int i = 0;
for(i = d; i >= 0; i--){
if((c & (1 << i)) != 0){
return 1;
}else{
return 0;
}
}
}
当我编译它时,我没有收到任何错误,但我的输出不正确:
Input a string of characters (no spaces):
eli
You typed: eli
The binary ASCII code for this string is: 2421936
无论我尝试什么输入,我都会得到返回值 2421936。关于我哪里出错的任何想法?
【问题讨论】:
标签: c string binary structure ascii