C++二进制转换为十进制,八进制

C++ convert binary to decimal, octal

本文关键字:八进制 十进制 二进制 转换 C++      更新时间:2023-10-16

请我需要帮助调试下面的代码。我假设使用将二进制数转换为十进制或八进制的函数生成代码。我在 switch 语句"函数调用中的参数错误太少"中不断收到错误。

#include <iostream.> 
long int menu();
long int toDeci(long int);
long int toOct(long int);
using namespace std;
int main () 
{
int convert=menu();
switch (convert)
{
case(0):
    toDeci();
    break;
case(1):
    toOct();
    break;
    }
return 0;
}
long int menu()
{
int convert;
cout<<"Enter your choice of conversion: "<<endl;
cout<<"0-Binary to Decimal"<<endl;
cout<<"1-Binary to Octal"<<endl;
cin>>convert;
return convert;
}
long int toDeci(long int)
{
long bin, dec=0, rem, num, base =1;
cout<<"Enter the binary number (0s and 1s): ";
cin>> num;
bin = num;
while (num > 0)
{
rem = num % 10;
dec = dec + rem * base;
base = base * 2;
num = num / 10;
}
cout<<"The decimal equivalent of "<< bin<<" = "<<dec<<endl;
return dec;
}
long int toOct(long int)
{
long int binnum, rem, quot;
int octnum[100], i=1, j;
cout<<"Enter the binary number: ";
cin>>binnum;
while(quot!=0)
{
    octnum[i++]=quot%8;
    quot=quot/8;
}
cout<<"Equivalent octal value of "<<binnum<<" :"<<endl;
    for(j=i-1; j>0; j--)
    {
        cout<<octnum[j];
    }
}

我假设使用将二进制数转换为十进制或八进制的函数生成代码。

没有像根据数字表示将二进制数转换为十进制或八进制这样的事情,例如

long int toDeci(long int);
long int toOct(long int);

对于任何语义解释来说,这样的功能都是完全荒谬的。

数字

是数字,其文本表示形式可以是进制、十六进制八进制或二进制格式:

dec 42
hex 0x2A
oct 052
bin 101010

long int数据类型中仍然是相同的数字。


使用 c++ 标准 I/O 操纵器,可以从这些格式的文本表示形式进行转换。

我不确定我是否理解你想做什么。下面是一个可能对您有所帮助的示例(演示):

#include <iostream>
int main()
{
  using namespace std;
  // 64 bits, at most, plus null terminator
  const int max_size = 64 + 1;
  char b[max_size];
  //
  cin.getline( b, max_size );
  // radix 2 string to int64_t
  uint64_t i = 0;
  for ( const char* p = b; *p && *p == '0' || *p == '1'; ++p )
  {
    i <<= 1; 
    i += *p - '0';
  }
  // display
  cout << "decimal: " << i << endl;
  cout << hex << "hexa: " << i << endl;
  cout << oct << "octa: " << i << endl;
  return 0;
}