I know how pointers work, but I'm having some trouble understanding this cast with pointers.
float f;
scanf("%f", &f);
unsigned int x = *(unsigned int*)&f;
Can someone explain me how this works?
I know how pointers work, but I'm having some trouble understanding this cast with pointers.
float f;
scanf("%f", &f);
unsigned int x = *(unsigned int*)&f;
Can someone explain me how this works?
unsigned int x = *(unsigned int*)&f;
basically means "take the address of f
, pretend it's an address to an unsigned int
instead of a float
, and dereference the result.
It's basically attempting to copy the bits from f
into x
without any type conversion.
As mentioned in the comments, this breaks a rule known as the "strict aliasing rule", and the behavior on doing so is undefined. This may work as expected. It may not.
Just an addition to @John Bode's answer, try (and maybe debug) the following code to make things clear.
It's like, looking at the same bit pattern;
float
set of eyeglasses,int
set of eyeglasses.#include <stdio.h>
#include <stdlib.h>
void printBits(int k) {
char bitStr[33];
// put a string terminator at end of string
bitStr[32] = '\0';
for (int i = 0; i < 32; i++) {
if (k & 1) {
bitStr[31 - i] = '1'; // if 32nd bit is 1
}
else {
bitStr[31 - i] = '0'; // if 32nd bit is 0
}
k = k >> 1; // shift all bits 1 bit right, dropping the right most (32nd) bit
}
printf("%s", bitStr);
return;
}
int main()
{
float f = 1.0f;
int i = *(int *)&f;
printf("bit pattern ");
printBits(*(int *)&f);
printf(" equals to %f in float\n", f);
printf("bit pattern ");
printBits(i);
printf(" equals to %d in integer\n", i);
return 0;
}