Thursday, July 29, 2010

Back to Basics: C Basic Types and Their Representation in Memory

Great lectures Stanford put online http://www.youtube.com/watch?v=jTSvthW34GU 
The linked lecture explains very nicely two's complement are 15:00. Other great lectures in this series called Programming Paradigm.

Something I liked is that the lecturer explained why two's complement system is used to represent negative numbers. In short basically it makes basic operation like addition and subtraction really easy for hardware and thus fast. Examples are given in the lecture to illustrate.
see near the end of the lecture where representing floating-point numbers is discussed.
#include 
int main()
{
 int i = 37;
 float f = * (float *) &i;

 printf("%f\n",f);

 return 0;
}
You'll see why the code above does not print what one thinks it might print it first glance. By dereferencing a float point cast from the address of i, we're causing f to have the same pattern of 37 when interpreted as int but not the value 37.




No comments:

Post a Comment