整数转化为2进制补码(双指针的一种变形)
#include <iostream> #include "algorithm" #include "cmath" #include "string" #include <vector> using namespace std; int main() { int sav[8]={1,2,4,8,16,32,64,128};//2^n事先存储 int er[8]={0};//存储二进制01 int phigh=7; int cur=0; int sum=100; while(phigh>=0){ cur+=sav[phigh]; if(cur>sum){ cur-=sav[phigh]; //cout<<"情况1"<<cur<<endl; phigh--;//之前忽略了这个 //cur=0; } else if(cur==sum){ er[phigh]=1; //cout<<"情况2"<<cur<<endl; break; } else if(cur<sum){ er[phigh]=1; //cout<<"情况3"<<cur<<endl; phigh--; } } for(int i=0;i<8;i++){ cout<<er[i]; } }
也可以不用事先存储:(只适合正整数求补码)
#include <iostream> #include "algorithm" #include "cmath" #include "string" #include <vector> #include "bitset" using namespace std; int main() { //如果只是输出就不用事先存储了 int phigh=7; int cur=0; int num=0;//位数 int sum=100; while(phigh>=0){ cur+=pow(2,phigh); if(cur>sum){ cout<<0;num++; cur-=pow(2,phigh); phigh--;//之前忽略了这个 } else if(cur==sum){ cout<<1;num++; break; } else{ cout<<1;num++; phigh--; } } for(int i=1;i<=8-num;i++){//默认8位 cout<<0; }cout<<endl; }
常规解法:(只适合正整数求补码)
#include <iostream> #include "algorithm" #include "cmath" #include "string" #include <vector> using namespace std; int main() { int sum=100; vector<int> res; while(sum){ res.push_back(sum%2); sum=sum/2; } reverse(res.begin(),res.end()); for(vector<int>::iterator it=res.begin();it!=res.end();it++) cout<<*it; }
库函数://正负数都可以
#include<iostream> #include<cstdio> #include<bitset> using namespace std; int main() { bitset<8> t=-125; cout<<t; return 0; }
不一样的烟火