【问题标题】:How to use my output for another equation?如何将我的输出用于另一个方程?
【发布时间】:2019-08-09 09:20:57
【问题描述】:

所以我有一个问题,我想不通,如果有人可以帮我处理我的代码,我会很高兴。所以我正在使用 INPUT 和 OUTPUT 函数将字节转换为位,我的问题是我找不到一种方法来自动使用结果(输出)也以二进制形式计算它。因此,如果我想将 50 B 转换为位,我将得到 400,而这 400 位(numbit)我希望它们也像二进制一样显示。这是我的代码:

#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");
}
}

【问题讨论】:

  • 请不要使用与您的问题无关的编程语言标签。
  • 不相关,但在假设一个字节为 8 位之前,您应该阅读以下内容:stackoverflow.com/q/11600378/3723423
  • @Christophethanx 的提示。
  • 尚不完全清楚 numBit 是一个大小(例如转换为位数的字节数)还是您只想将此数字转换为可打印的位序列。
  • @Ben 哦,你认为与我的问题无关的标签是什么?

标签: c++ binary byte


【解决方案1】:

更新:BONUS-Round 现在有带符号和无符号数字(注意有符号表示取决于实现,即编译器、字节序、操作系统,无符号长度相同)

#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";
    }
}

【讨论】:

  • 祝福你,它将数字转换为二进制,但我找到了一种让它对我有用的方法。再次感谢您的时间,兄弟...
猜你喜欢
  • 2017-05-11
  • 2019-06-13
  • 1970-01-01
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
相关资源
最近更新 更多