调试整数到二进制代码?不转换32、64
debugging integer to binary code? doesnt convert 32, 64
所以这是我的问题,我(我认为)是一个不错的代码部分,它似乎适用于我投入的大多数数字。但是,当我放入2^x
时数字(例如32
或64
)它返回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;
}
相关文章:
- 努力将整数转换为链表。不知道我在这里做错了什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 如何在C++中将整数转换为其数字数组
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 如何将整数字符串转换为整数的二维向量?
- 如果整数与指针大小相同,则重新解释将整数转换为指针双射是否具有双射作用?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 如何检测 std::vector::emplace_back 上的隐式转换损失整数精度
- 如何防止双精度值到整数的隐式转换
- 为什么此指针值不能转换为整数的规则是什么?
- 如何解决隐式转换丢失整数精度:'size_t'(又名"无符号长")到'int'警告?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- 为什么在将 void 指针转换为整数指针时出现分段错误
- 将字符串(可以是十进制字符串或十六进制字符串)转换为整数C++
- 整数类型应该显式转换(例如"int"到"无符号")还是只会增加混乱?
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 无法将"整数 (*)[m]"转换为"整数 (*)[100000]
- 静态强制转换允许转换对象指针,但不允许转换整数