编写将二进制转换为文本的程序 c++6

Writing a program that converts binary into a text c++6

我试图查找与我的问题相关的内容,但似乎没有任何内容能够以我能理解的方式完全回答它们。

所以,我开始了:我们有一个文件,它是十进制的。我们必须编写一个程序,将其转换为字符(基本上我们需要对其进行解码)。

那么我想做什么:

  1. 编写一个将二进制转换为十进制的函数(已完成)
  2. 编写一个函数,将这些转换后的小数转换为字符
  3. 编写主要功能,将它们连接在一起。

我卡在第 2 点了。如何编写将十进制转换为 ASCII 的程序?

如果我完成了那个,我该如何包含文件 nzz.in?我不应该只写

#include <nzz.in>

然后就收录了?

以下程序将为您服务:

让我们有一个名为 converters.h 的头文件,其内容如下:

/* 
 * File:   converters.h
 * Author: Praveen
 *
 * Created on 13 December 2016, 8:59 PM
 */

#ifndef CONVERTERS_H
#define CONVERTERS_H

int toDecimal(int num) {
    int rem = 0;
    int dec = 0;
    int base = 1;
    while (num > 0) {
        rem = num % 10;
        dec = dec + rem * base;
        base = base * 2;
        num = num / 10;
    }
    return dec;
}

char toChar(int value) {
    return char(value);
}

#endif  /* CONVERTERS_H */

现在让我们定义程序必须运行的文件,名称为testMain.cpp,代码如下:

#include<iostream>

#include "converters.h"

int main() {
    int num;
    std::cout << "Enter the binary number(1s and 0s) : ";
    std::cin >> num;

    int decVal = toDecimal(num);

    std::cout << "The decimal equivalent of " << num << " is : " << decVal << std::endl;

    char charVal = toChar(decVal);
    std::cout << "The character equivalent of " << decVal << " is : " << charVal << std::endl;

    return 0;
}

运行上面程序的示例输出:

Enter the binary number(1s and 0s) : 1000001
The decimal equivalent of 1000001 is : 65
The character equivalent of 65 is : A

请根据您的需要修改头文件名或程序名。