[THINKING IN C++]CHAPTER 03:EX 25

本文通过定义一个浮点变量并使用指针操作,展示了如何查看和修改浮点数在内存中的二进制表示形式。文章包括了C++代码示例,详细解释了如何将浮点数地址转换为字符指针,并利用此指针打印出浮点数的位模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//25. Define a float variable. Take its address, cast that address
//to an unsigned char, and assign it to an unsigned char
//pointer. Using this pointer and [ ], index into the float
//variable and use the printBinary( )function defined in
//this chapter to print out a map of the float (go from 0 to
//sizeof(float). Change the value of the float and see if
//you can figure out what’s going on (the float contains
//encoded data).

//这题要看书p189的例子

#include
<iostream>
using namespace std;

void main() {
    
float fv;
    unsigned 
char *= reinterpret_cast<unsigned char*>(&fv);
    
    
void printBinary(const unsigned char);

    cout
<<"fv= "<<fv<<endl;
    
for(int j = 0; j < sizeof(float); j++){
        cout
<<"p["<<j<<"]:";
        printBinary(p[j]);
        cout
<<endl;
    }
}

//: C03:printBinary.cpp {O}
void printBinary(const unsigned char val) {
  
for(int i = 7; i >= 0; i--)
    
if(val & (1 << i))
      std::cout 
<< "1";
    
else
      std::cout 
<< "0";
///:~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值