R
R
r1ch2013-12-09 22:51:30
C++ / C#
r1ch, 2013-12-09 22:51:30

Type conversion in si?

int i = 37; // 00000000000000000000000000100101 = 0.00000000.00000000000000000100101 = ((-1)^0)*1,00000000000000000100101*2^-127 = 1,00000000000000000100101*(1/1,701419339096245668434929897641e+38) = 0,000000
float f = *(float*)&i; // 0,000000

int i = -37; // 11111111111111111111111111011010 = 1.11111111.11111111111111111011010 = ((-1)^1)*1,1111111111111111111111111011010*2^255-127= -1,999999982304871082305908203125*3,4028236692093846346337460743177e+38 = -6,8056472782053657584265955775406e+38 
float f = *(float*)&i; // -1.#QNAN0 

float f = 7.0; // 0.10000001.11000000000000000000000 = 1088421888
int i = *(int*)&f; // 1088421888

float f = -7.0; // 1.01111110.00111111111111111111111 = -1059061760
int i = *(int*)&f; // -1059061760

SI code. By what algorithm does this code get from int => float, float => int, how is the mantissa and exponent converted to an integer?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AM5800, 2013-12-09
@AM5800

To answer your question about the algorithm: none.
You are casting pointers here.
That is, in the first case, you have some memory cell that contains the number 37. If you forget about types for a moment, then this cell contains the value "...0100101"
When you take its address (&i) - you get a pointer type int. After casting, you get a float pointer. The type of the pointer changes, but not the data it points to. After the dereference and assignment, you get the variable f, whose value is still "...0100101".
If you are interested in a float device. Then, you can start from here:
en.wikipedia.org/wiki/Single-precision_floating-po...

S
svd71_1, 2013-12-09
@svd71_1

The algorithm is simple: the compiler takes the memory area under the variable and tries to represent it as a different type. At the same time, there is no type compatibility check: an int contains a sequence of bits in 4 bytes, a float has two parts - a real and a mantis. If the type being converted is larger than the original type, then there will be all sorts of junk in the data.

I
Ilya Evseev, 2013-12-10
@IlyaEvseev

If sizeof(int) != sizeof(float), you can earn very interesting hemorrhoids on your ass.
Worst of all, such code has actually been encountered in production (!!!) in commercial codecs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question