我有一个 C++ 代码,它将 2 位八进制数转换为二进制数。为了测试代码的有效性,我使用了几个在线转换站点,例如
当我输入 58 或 59 作为八进制值时,它表示八进制值无效,但是当我在代码中输入 58 时,它给出的二进制数为 - 101000。再次进行测试时,我在上面网站的计算器中输入 101000 作为二进制数然后他们给我结果50 作为八进制值。
我需要一些解释为什么会这样。
这是 C++ 代码 -
#include <iostream.h>
#include <conio.h>
void octobin(int);
void main()
{
clrscr();
int a;
cout << "Enter a 2-digit octal number : ";
cin>>a;
octobin(a);
getch();
}
void octobin(int oct)
{
long bnum=0;
int A[6];
//Each octal digit is converted into 3 bits, 2 octal digits = 6 bits.
int a1,a2,quo,rem;
a2=oct/10;
a1=oct-a2*10;
for(int x=0;x<6;x++)
{
A[x]=0;
}
//Storing the remainders of the one's octal digit in the array.
for (x=0;x<3;x++)
{
quo=a1/2;
rem=a1%2;
A[x]=rem;
a1=quo;
}
//Storing the remainders of the ten's octal digit in the array.
for(x=3;x<6;x++)
{
quo=a2/2;
rem=a2%2;
A[x]=rem;
a2=quo;
}
//Obtaining the binary number from the remainders.
for(x=x-1;x>=0;x--)
{
bnum*=10;
bnum+=A[x];
}
cout << "The binary number for the octal number " << oct << " is " << bnum << "." << endl;
}