Wednesday 6 November 2013

Fun with Data Manipulation

Once again, my friend Adam found a good resource for learning more about C/C++ and computer science. It is a series of YouTube videos of Professor Jerry Cain of Stanford University teaching his CS107 class and it is informative and interesting to watch (almost as entertaining as Fardad's lectures). I really recommend students to watch those videos if they are interested in learning about the concepts that were taught up to now but wanted to know more in depth. In regards to these videos, it taught me how floating point numbers are represented bitwise, which is more complex than integers. The videos did a very nice job explaining this. Also, I really like how Professor Cain manipulates the data to show students how information is read and written in memory. By understanding things at a lower level, it makes the process clearer (at least for me). While teaching about types like structs and arrays, he would show examples of stored data represented in bits and bytes and will do various casts, address incrementation/decrematation, and manipulate their value in such a way that the output can be determined by knowing the size of these types. Here's an example:

int arr[5];                 // sizeof(int) = 4, sizeof(short) = 2
                         
arr[3] = 128;            // 3 * 4 bytes each [  |  |  |  ][  |  |  |  ][  |  |  |  ][A |   |  |  ][  |  |  |  ] write at 12th byte
                                 // A = binary 10000000 = decimal 128
                                        
((short*)arr)[7] = 2; // 7 * 2 bytes each [  |  |  |  ][  |  |  |  ][  |  |  |  ][ A |  B |  ][  |  |  |  ] write at 14th byte
                                 // B = binary 00000010 = decimal 2

cout << arr[3] << endl; // It will read this as an integer: 00000000 00000010 00000000 10000000

// Output is 131200

I should also mention that this example was created on the matrix server and the machines are little endian meaning they store the least significant byte in the smallest address first (so the above would normally be read as [  B |   | A ]. Pretty cool stuff.

https://github.com/wongbsn/Codepad/blob/master/Bitwise%20Operation%20and%20Representation/data1.cpp

0 comments:

Post a Comment