owe*_*inh 0 c++ floating-point
所以我到目前为止:
#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;
}
Run Code Online (Sandbox Code Playgroud)
the result is: -51 -52 92 64
所以很明显-51和-52不在我期望的字符范围内...我已经从类似的问题中获取信息以得到这个代码,并且从所有的讨论中,从char到int的转换是直截了当的.那么为什么负值呢?我试着看一个四字节的数字,因此我希望有4个整数,每个整数在0-255范围内.
我在Windows 8.1设备上使用带有gcc 4.8.1的Codeblocks 13.12和选项-std = C++ 11.
编辑:所以解决方案是使用:
unsigned char* ptr = reinterpret_cast<unsigned char*>( &f );
Run Code Online (Sandbox Code Playgroud)
谢谢你的回复.
使用unsigned char以获得(保证)无符号值.
你得到负值,因为你的编译器和编译器选项(是的,重要的)char是签名类型.
顺便说一句,前缀+运营商是促进一个方便,简洁的方式char来int,用于显示数值的目的.
另外,顺便说一句,这是使用C++命名蒙上了一般好主意(reinterpret_cast,const_cast,static_cast和dynamic_cast)而不是C风格的转换,其中三分球有关.这是因为C样式转换可以最终做出意想不到的事情,特别是在代码被维护和类型改变时.在这种情况下,你正在表达一个reinterpret_cast,所以这是一个使用 - 只是为了好习惯的缘故.
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |