I know the reinterpret_cast in C++ can be used in this way:
float a = 0;
int b = *reinterpret_cast<int*>(&a);
But why cannot cast it directly?
float a = 0;
int b = reinterpret_cast<int>(a);
error: invalid cast from type 'float' to type 'int'
The reinterpret_cast operator converts a null pointer value to the null pointer value of the destination type.
Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.
C-style casts can be used to convert any type into any other type, potentially with unsafe results (such as casting an integer into a pointer type). (<type>)<value> This example casts an int to a double for the purpose of avoiding truncation due to integer division: double result = (double)4/5; Popular pages.
All reinterpret_cast
does is allow you to read the memory you passed in a different way. You give it a memory location and you ask it to read that memory as if it was what you asked it to. This is why it can only be used with pointers and references.
Let's take this code as an example:
#include <iostream>
int main()
{
float a = 12;
int b = *reinterpret_cast<int*>(&a);
std::cout << b;
}
So to break this line of code into more details *reinterpret_cast<int*>(&a);
:
a
reinterpret_cast
to an int*
int*
that points to a
int
Now when I run this I get 1094713344
, the reason for that is 12 as a float
using IEEE is represented as 0100 0001 0100 0000 0000 0000 0000 0000
in binary. Now take that binary and read it as unsigned int
, then you end up with 1094713344
.
This is why reinterpret_cast
is considered to be very dangerous and why it should NOT be used in this type of cases.
You should only use it when you have a pointer pointing to memory and you need to read that memory in a certain way and you know that the memory can be read in that way.
You can't reinterpret_cast in the case you give because reinterpret_cast takes only either a int to convert to a pointer, or the reverse, and follows additional similar rules.
There is a summary of these rules there: http://en.cppreference.com/w/cpp/language/reinterpret_cast
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