Are there any advantages from doing conversion like this
int i = 1024;
byte b = (byte)i;
over doing this
int i = 1024;
byte b = *((byte*) &i);
I mean, if you want to use the second method you must use unsafe code, that means that the JIT can’t optimize it as it wishs (I think it’s doing internally the second way) and so on.
Can somebody explain me when and why to use the first / the second method?
Greetings
Those two are not equivalent.
The first is a simple language defined cast. Its result is well defined: The first one returns the 8 least significant bits.
The second is effectively a reinterpret-cast. It returns the first 8 bits in memory. Which happen to be the same on typical little-endian systems, but differ on big-endian systems.
There are a few rare instances where reinterpret-casts are useful, but this isn’t one of them. You should always use normal casts, unless you have a problem that can only be solved with reinterpret casts.