Tuesday 5 November 2013

About Casting and Data Representation

I've decided to try this blogging business a bit more in hopes that it can help me review and understand concepts a bit better and write down special events that may be worth remembering. Today I believe such an event happened at Seneca. During my OOP344 class, Professor Chris Szalwinski came in to inform us that a course on parallel programming will be available next Fall. Parallel programming is apparently a new and growing thing and the idea of working with multiple cores and with the GPU sounds difficult but exciting. This will be one of the courses I will defiantly consider taking once I get back from my co-op position at RBC. Hopefully, everything will go as planned and I will be able to take that course.

One of the things I enjoy doing at Seneca is learning new concepts with friends and classmates. Today, my friend Adam taught me a bit more about casting. He begins by talking about variables and how they contain a number of information that is important to the compiler such as the identifier, type, address, value, scope, and lifetime. When stored in memory, a variable's type is associated with its identifier, value-set, and value-bit representation. One example he showed us was this:

unsigned int x = 1000;
int y = -1;

if(y > x) std::cout << "y is bigger" << std::endl; // This gets called

What happened was that when comparing a signed with an unsigned, the signed will be implicitly casted as an unsigned, making this -1 into 4.2 billion something. This is understood using modular or clock arithmetic and how numbers are represented in bits. To further explain this, he illustrates the difference between static and reinterpret casting. In a static cast, the value is preserved and the bit pattern is changed whereas in a reinterpret cast, the value is modified and the bit pattern is preserved. What happened is this, -1 is not within the value-set of unsigned integers (0 to 4.2 billion) so the compiler cannot fix the value and modify the bit pattern (static cast) so then it will do a reinterpret cast by looking at the association between the bit patterns and values, and then reads it off as a normal unsigned integer.

            Signed                         Unsigned
<-1, ... ... ... 11111111><4.2B, ... ... ... 11111111>
< 0, ... ... ... 00000000>     <0, ... ... ... 00000000>
< 1, ... ... ... 00000001>     <1, ... ... ... 00000001>


0 comments:

Post a Comment