简体   繁体   English

需要在内存 C++ 中将浮点数作为 HEX

[英]Need to a put a float as HEX in memory C++

Title.标题。 Need to put bridgeSymbol hex value into myVariable memory buffer.需要将bridgeSymbol十六进制值放入myVariable内存缓冲区。 I've tried every cast that came to my mind (bit_cast, reinterpret_cast).我已经尝试了所有想到的转换(bit_cast、reinterpret_cast)。

Expected result should be hex value of (float)bridgeSymbol at myVariable pointer address.预期结果应该是myVariable指针地址处的(float)bridgeSymbol的十六进制值。

What I'm missing?我缺少什么?

uintptr_t myVariable = 0xC70BBF5C;

float bridgeSymbol = *(float*)(&myVariable);        //Big endian -35775.36 OK!
bridgeSymbol = bridgeSymbol / 10;                   //some random operation  = -3577.5

myVariable = (uintptr_t)bridgeSymbol;               //expected 0xc55f9800 but getting random values

Edit 1: More detailed explanation as suggested.编辑 1:建议的更详细的解释。

Here's something closer to what you want.这里有一些更接近你想要的东西。

 static_assert(sizeof(float) == 4);
 myVariable = *(uint32_t*)(&bridgeSymbol);

Above is basically saying, treat the 4 bytes of memory occupied by the float as a 32-bit uint, and then assign back to myVariable.上面基本上就是说,把float占用的4字节内存当成一个32位的uint,然后赋值回myVariable。 It's literally the opposite of what you are doing to convert the original value into a float.这实际上与您将原始值转换为浮点数所做的相反。

The trouble is that your myVariable is declared as uintptr_t, which is 32-bit on a 32-bit platform.问题是你的myVariable被声明为 uintptr_t,它在 32 位平台上是 32 位的。 But as soon as your code compiles for 64-bit, it will be a 64-bit number.但是一旦您的代码编译为 64 位,它将是一个 64 位数字。

A float is almost always 32-bit on any architecture.在任何体系结构上,浮点数几乎总是 32 位的。 So I'd recommend you declare myVariable as a uin32_t as well.所以我建议您也将myVariable声明为 uin32_t。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM