CISC181 010-012 09/14/05 05F Attendance: (1.1) Review: Conversion from decimal to binary by hand 271 in decimal is what in binary? 271 - 256 = 15 15 - 8 = 7 7 - 4 = 3 3 - 2 = 1 1 - 1 = 0 So the bits are 256, 8, 4, 2, 1 as shown here: 512 256 128 64 32 16 8 4 2 1 0 1 0 0 0 0 1 1 1 1 (1.2) Meaning of % and / with integers in C, C++, Java 271 % 2 is read "two seventy one mod two". % is remainder after division. (1.3) A technique to convert from decimal to binary using % and / 271 % 2 => 1 271 / 2 => 135 135 % 2 => 1 135 / 2 => 67 67 % 2 => 1 67 / 2 => 33 33 % 2 => 1 33 / 2 => 16 16 % 2 => 0 16 / 2 => 8 8 % 2 => 0 8 / 2 => 4 4 % 2 => 0 4 / 2 => 2 2 % 2 => 0 2 / 2 => 1 1 % 2 => 1 1 / 2 => 0 What we get from the results of the % operations is the bits of the number we started with, in reverse order. (From least significant to most significant). 512 256 128 64 32 16 8 4 2 1 0 1 0 0 0 0 1 1 1 1 (1.4) Review from last time about character data... and a bit more information... "ADAMS" in memory can be represented with (at least) two types of strings: (1) C-Strings.... (2) C++ "string" class. C-strings are just arrays of characters, terminated with the '\0'. The '\0' is different from the '0' character. The '0' character prints the actual symbol for zero (a kind of skinny tall oval.) The '\0' is never printed... instead, it is a kind of internal stop sign to tell the computer when to stop processing a string. It is, the words of the Gov. of Calif. the "null terminator". ADAMS in memory is represented by 6, not 5, consecutive byte. How many bits in a byte? eight bits in a byte. What's half a byte? A nibble (four bits). So altogeher, in ADAMS, there are 48 bits. characters A D A M S \0 ascii values 65 68 65 77 83 0 (in decimal) in binary: 0100 0001 0100 0100 0100 0001 0100 1101 0101 0011 0000 0000 (1.5) Going back to the algorithm for converting decimal to binary with repeated % and / ... This raises a question: Can we make this a function? Use a C string as our target: char binaryAnswer[9]; Limitations: min 0 minimum value for decimal input max 255 maximum value for decimal input number of bits in binary answer 8 represent the binary answer as a C string char binaryAnswer[9]; Note the role of \0 '0' in binary is 0010 1000 '1' in binary is 0010 1001 '\0' in binar is 0000 0000 [null terminator] void computeBinary (int decVal, char binAns[9]) { for (int i = 0; i<8, i++) binAns[i] = '0'; binAns[8] = '\0'; @@@ FILL IN DETAILS HERE return; } (1.9) Slight digression littleHat.cc int main(void) { int a = 2^3; cout << a << endl; // does this print 8? } See the file littleHat.cc for more fun with exclusive or (XOR) and with exponents. By the way, "make littleHat" automatically brings up a compile command: CC -o littleHat littleHat.cc Later, we'll see how we can customize the "make" utility with a "Makefile" to use g++ instead of CC, use .cpp instead of .cc, and other fun things. (2) Now let's look at binConvert.cc