一个简单的将二进制转换为十进制的程序--- 位操作练习题

# include <stdio.h>
# include <string.h>
# define LEN 32            //规定字符串的长度为32,对应32位

int be_val(const char* ps);
char* s_gets(char* str, int n);

int main()
{
    char pbin[LEN];

    puts("Please enter the binary.Support 32 bits .");
    while (s_gets(pbin, LEN) != NULL && pbin[0] != '\0')
    {
        int dec;
        dec = be_val(pbin);

        printf("%d\n", dec);
        puts("Please enter next binary");
        puts(" Press 【enter】 at the beginnning of the new line to quit");
    }
    puts("bye");
    

}
int be_val(const char* ps) { int i = strlen(ps)-1; //计算字符串长度,并减去1,作为循环条件用 int sum = 0; int j = 1; int num; //位的情况:1或0 int val; int k = strlen(ps)-1; //同int i while (*ps!='\0') { i = k; num = (*ps) - '0'; if (num) //为1,则进入;不然跳过此判定 { val = 1; while (i) { val = val * 2; i--; }; sum += val; } k--; ps++; } return sum; } char* s_gets(char* str, int n) { char* ret_val; char* find; ret_val = fgets(str, n, stdin); if (ret_val) { find = strchr(str, '\n'); if (find) *find = '\0'; else while (getchar() != '\n') continue; } return ret_val; }

 

posted @ 2022-03-10 16:17  Tolerieren  阅读(173)  评论(0)    收藏  举报