我试图访问浮点数中的单个字节,我得到了意想不到的结果
I am trying to access the individual bytes in a floating point number and I am getting unexpected results
到目前为止我有这个:
#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_cast
和dynamic_cast
)而不是C风格的强制转换,这通常是一个好主意,其中涉及指针。这是因为C风格强制转换可能会导致意想不到的结果,特别是在维护代码和更改类型时。在这种情况下,您表示的是reinterpret_cast
,因此要使用& &;看在好习惯的份上
相关文章:
- 为什么在递归中使用循环会产生意想不到的结果?
- 字符到int8_t转换会产生意想不到的结果?
- libc++ 对 std::map/set::equal_range 的实现给出了意想不到的结果
- 微小加密算法实现会产生意想不到的结果
- 使用 std::set 的 .begin() 和 .end() 函数会产生意想不到的结果
- 在我的C++链表实现中取消引用节点指针,给出意想不到的结果
- C++正则表达式Visual Studio Community 2015给出<regex>意想不到的结果
- istringstream int8_t产生意想不到的结果
- 划分 OpenCV 垫会产生意想不到的结果
- 提升精神,提升任何意想不到的结果
- regex_match给出意想不到的结果
- 从 PASCAL 到 C++ 的代码转换给出了意想不到的结果
- 意想不到的结果c++
- 在lambda上使用条件运算符调用std::any_of会得到意想不到的结果
- vector::insert在VS2010中执行意想不到的结果
- list resize会产生意想不到的结果
- CUDA: 2D数组索引产生意想不到的结果
- 将字符串转换为整数会产生意想不到的结果
- 在c++中,一些宏语句可能会产生意想不到的结果
- Visual Studio可变宏展开会产生意想不到的结果