所以我有一个问题,我无法解决,如果有人可以帮助我编写代码,我将很高兴。所以我正在使用INPUT和OUTPUT函数将字节转换为位,我的问题是我也找不到自动使用结果(输出)以二进制形式进行计算的方法。因此,如果我想将50 B转换为位,结果将得到400,而这400位(数字位)我也希望它们也像二进制一样显示。这是我的代码:
#include<iostream>
#include<conio.h>
using namespace std;
main()
{
int numB, numbit;
int arr [100], i = 0,j;
//INPUT
cout<<"Please Enter the number of Bytes:";
cin>>numB;
cout<<"\n";
//Formula bytes into bits
numbit = numB * 8;
//OUTPUT
cout<<"Is equal to the number of bits:"<<numbit;
cout<<"\n";
while (numbit>0)
{
arr [i] = numbit%2;
i++;
numbit=numbit/2;
}
cout<<"Binary number is: ";
for (j= i-1; j>=0; j--)
{
cout<< arr[j];
return 0;
system("Pause");
}
}
答案 0 :(得分:1)
更新:BONUS-Round 现在都带有带符号和无符号数字(请注意,带符号的表示形式取决于实现,即编译器,字节序,操作系统,与无符号长度相同)< / p>
#include <iostream>
#include <bitset>
#include <cstdint>
int main()
{
{
unsigned unsigned_number{};
std::cout << "Please Enter an unsigned:";
std::cin >> unsigned_number;
std::bitset<CHAR_BIT * sizeof(unsigned)> bits{unsigned_number};
std::cout << "\nIs equal to the number of bits:" << bits << "\n";
}
{
int32_t signed_number{};
std::cout << "Please enter a signed:";
std::cin >> signed_number;
std::cout << "\nIs equal to the number of bits:";
for (int i = 0; i < 4; ++i) {
auto byte = reinterpret_cast<uint8_t*> (&signed_number) + i;
std::bitset<8> bits{*byte};
std::cout << bits;
}
std::cout << "\n";
}
}