指针强制类型转换的本质

例题:

#include <iostream>
#include <stdio.h>
#define ll long long
using namespace std;
int ans[100];
int main(){
	double d;
	cin >> d;
	ll p=*(ll *)&d;
	int cnt=0;
    for(;cnt<64;)
    {
        ans[++cnt]=p&1;
        p>>=1;
    }
    for(int i=cnt;i>=1;i--)
    printf("%d",ans[i]);
	return 0;
} 

以上代码就算是负数也可以的

但是如果把上面代码的ll p=*(ll *)&d;改成int p=*(int *)&d;会输出什么?

此时会p的机器表示是d的机器表示的后三十二位

当然下面的代码也是对的

#include <iostream>
#include <stdio.h>
#include<bits/stdc++.h> 
#define ll long long
using namespace std;
int ans[100];
int main(){
	double d;
	cin >> d;
	char *p=(char *)&d;
	for(int i=7;i>=0;i--)
	for(int j=7;j>=0;j--)
	cout<<(int)(p[i]>>j&1);
	return 0;
} 

所以\(p[0]\)其实是第八个字节,依次类推

posted @ 2023-11-29 22:36  最爱丁珰  阅读(8)  评论(0编辑  收藏  举报