Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of CPP reinterpret_cast

Tags:

python

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.

like image 452
Ravi Joshi Avatar asked Jul 24 '18 15:07

Ravi Joshi


People also ask

Is reinterpret cast compile time?

None of the casts happen at compile time. You only have the data at runtime, in general.

What does reinterpret_cast mean in C++?

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.

Is it safe to use reinterpret_cast?

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.


1 Answers

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

like image 121
Andrej Kesely Avatar answered Sep 29 '22 15:09

Andrej Kesely