简体   繁体   中英

Need to a put a float as HEX in memory C++

Title. Need to put bridgeSymbol hex value into myVariable memory buffer. I've tried every cast that came to my mind (bit_cast, reinterpret_cast).

Expected result should be hex value of (float)bridgeSymbol at myVariable pointer address.

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.

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. 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. But as soon as your code compiles for 64-bit, it will be a 64-bit number.

A float is almost always 32-bit on any architecture. So I'd recommend you declare myVariable as a uin32_t as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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