Re: printf("%d",float)
- From: andreyvul <andrey.vul@xxxxxxxxx>
- Date: Tue, 30 Oct 2007 19:07:31 -0700
On Oct 30, 8:48 pm, candy_i...@xxxxxxxxx wrote:
Hi all,
I just came across the following program:
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}
The program prints 0 and 1095237362. However, in my opinion it should
print 12 at both the places. Can anybody tell me where I am wrong?
Pointer casting does not convert values of one type to another. Your
code is sort of like this:
struct {
char a;
} A ;
struct {
float b;
} B;
printf("%c", ((A*)&B)->a);
OR
printf("%f", ((B*)&A)->a);
The latter will segfault/crash.
If sizeof(int) != sizeof(float) your code would have *very* likely
crashed. This is one of the reasons why you should be *very* careful
with pointers and never do anything fancy when working with pointers
UNLESS YOU COMPLETELY KNOW WHAT IT DOES, WHY IT DOES THAT, AND ANY
SIDE-EFFECTS. Be very careful, *especially* when you need to pass
void* arguments and struct-cast the pointer to get the data.
Getting back to the different number,
float = [sign bit] [7 exponent bits] [23 mantissa bits]
12.5 = 0 10000010 10010000000000000000000
= 0x41480000
= 1095237632
That's where your number came from.
Source: http://en.wikipedia.org/wiki/Single_precision
.
- Follow-Ups:
- Re: printf("%d",float)
- From: Peter Nilsson
- Re: printf("%d",float)
- References:
- printf("%d",float)
- From: candy_init
- printf("%d",float)
- Prev by Date: Re: how to optimize a for loop
- Next by Date: Re: how to optimize a for loop
- Previous by thread: Re: printf("%d",float)
- Next by thread: Re: printf("%d",float)
- Index(es):
Relevant Pages
|