提取数据类型在内存中的二进制

 方法一:

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();

具体看https://www.cnblogs.com/RabbitHu/p/bitset.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值