方法一:
int main(){
int a[32];
for (int i = 31; i >=0; i--) {
a[i]=y&1;
y=y>>1;
}
}
这样就把int在内存中二进制提取出来了(负数和整数都可以)。同理其他类型也行。
int在内存中存储形式参考:https://blog.csdn.net/ly_w1989/article/details/50213011
问题:如何提取指定位数的补码形式?比如8位的有符号类型。
一定不能用char,char从键盘读取1,是ASCII的1,并且读-1时,读两次,一次是符号-,接下来才读1.
解决这个问题,可以继续用int类型。
#include<iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int a[2][32];
int x,y;
while(cin>>x>>y){
for (int i = 7; i>=0; i--) {
a[0][i]=x&1;
x=x>>1;
}
for (int i = 31; i >=0; i--) {
a[1][i]=y&1;
y=y>>1;
}
for (size_t i = 0; i < 8; i++) {
std::cout << a[0][i] <<" ";
}
std::cout <<endl;
for (size_t i = 0; i < 32; i++) {
std::cout << a[1][i] <<" ";
}
std::cout << endl;
}
return 0;
}
方法二
用c++的bitset。
int n;
bitset<8> b(n);
str1 = b.to_string();
int len1 = str1.length();