我试图访问浮点数中的单个字节,我得到了意想不到的结果

I am trying to access the individual bytes in a floating point number and I am getting unexpected results

本文关键字:结果 意想不到 单个 访问 浮点数 字节      更新时间:2023-10-16

到目前为止我有这个:

#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
int main ()
{
    float f = 3.45;           // just an example fp#
    char* ptr = (char*)&f;    // a character pointer to the first byte of the fp#?
    cout << int(ptr[0]) << endl; // these lines are just to see if I get what I 
    cout << int(ptr[1]) << endl; // am looking for... I want ints that I can 
    cout << int(ptr[2]) << endl; // otherwise manipulate.
    cout << int(ptr[3]) << endl;
}
<>之前结果是:-51年-52年9264之前

所以-51和-52显然不在我期望的字符的字节范围内…我从类似的问题中获取信息,得出这段代码,从所有的讨论中,从char到int的转换是直截了当的。那么为什么是负值呢?我试图查看一个四字节的数字,因此我期望4个整数,每个在0-255的范围内。

我在Windows 8.1设备上使用Codeblocks 13.12和gcc 4.8.1,选项-std= c++ 11。

编辑:所以解决方案是使用:

unsigned char* ptr = reinterpret_cast<unsigned char*>( &f );

感谢大家的回复

使用unsigned char来获得(有保证的)无符号值。

你得到负值,因为你的编译器和编译器选项(是的,这很重要)char是一个有符号的类型。


顺便说一下,前缀+运算符是一种方便、简洁的方法,可以将char提升到int,以显示数值。


此外,顺便说一下,使用c++命名的强制转换(reinterpret_cast, const_cast, static_castdynamic_cast)而不是C风格的强制转换,这通常是一个好主意,其中涉及指针。这是因为C风格强制转换可能会导致意想不到的结果,特别是在维护代码和更改类型时。在这种情况下,您表示的是reinterpret_cast,因此要使用& &;看在好习惯的份上