I got stuck in a trivial problem of reinterpret_cast
casting operator. Basically, in CPP, I have a float
variable which is used to create a uint32_t
variable using reinterpret_cast
as shown below-
float x = 2.2949836e-38;
uint32_t rgb = *reinterpret_cast<uint32_t*>(&x);
printf("rgb=%d", rgb); // prints rgb=16377550
I want to achieve the same in python. Please note that conventional int casting isn't producing the expected result.
None of the casts happen at compile time. You only have the data at runtime, in general.
reinterpret_cast is a type of casting operator used in C++. It is used to convert a pointer of some data type into a pointer of another data type, even if the data types before and after conversion are different. It does not check if the pointer type and data pointed by the pointer is same or not.
The reinterpret_cast operator can be used for conversions such as char* to int* , or One_class* to Unrelated_class* , which are inherently unsafe. The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type. Other uses are, at best, nonportable.
You can use pack
, unpack
from struct
module:
from struct import pack, unpack
b = pack('f', 2.2949836e-38)
print(unpack('i', b)[0])
Prints:
16377550
Edit:
shortened example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With