调试整数到二进制代码?不转换32、64

debugging integer to binary code? doesnt convert 32, 64

本文关键字:转换 整数 二进制 代码 调试      更新时间:2023-10-16

所以这是我的问题,我(我认为)是一个不错的代码部分,它似乎适用于我投入的大多数数字。但是,当我放入2^x时数字(例如3264)它返回10而不是10000000,这显然不正确。任何帮助将不胜感激。

#include <iostream>
#include <cmath>
#include <string>
using namespace std;
//void thework(unsigned int num); /*was going to take this another direction and decided not to*/

int main(){
    int num;
    int por;
    int mun;
    por = 64;
    cout<<"imput a number you want to convert to binary"<<endl;
    cin>>num;
start:
    if(num < pow(2.0,por)){ /*just to get the power widdled down to size*/
        por--;
        goto start;
    }
    /*part 2 is the "print 1" function, part 2 is the "print 0 and return to part 1, or kill section */
p2: 
    if((num >= (pow(2.0,por)))&&(num != 0)){
        cout<<"1";
        num -= pow(2,por);
        por--;
        goto p2;
    }
p3:
    if((num < pow(2,por))&&(num > (-1))){
        mun=num;
        if((mun -= pow(2.0,por)) > 0){
            cout<<"1";
            num -= pow(2.0,por);
            goto p2;
        }
        if((mun -= pow(2.0,por)) > 0){
            cout<<"0";
            num -= pow(2.0,por);
            por--;
            goto p2;
        }
        return 0;
    }

这是另一种方法,一些重要的细节

  • 仅使用int;使用双打是不必要的,并且可能是错误的来源
  • 基于大小的循环尺寸。
  • 使用0 == false,其他一切== true。只需掩盖问题的位即可避免需要担心以最高订单位设置的右移动值的实现特定行为。
  • 不使用goto。是的,goto在语言中,但是只有yacc才能摆脱它,人们不应该使用它。

来源

#include <iostream>
using namespace std;
int main(int argc,char *argv[])
{
   int num;
   cout << "input a number you want to convert to binary" << endl;
   cin >> num;
   for(int j = sizeof(num)*8 - 1;j >= 0;j--)
   {
      if(num & (0x1 << j)) cout << "1";
      else cout << "0";
   }
   cout << endl;
   return 0;
}