|
CS 2731, Spring 2004 |
Recitation 2 must be submitted
following directions at: submissions on or before
|
Outline: Recitation 2 is an introduction to binary arithmetic and representations of signed binary integers.
For this recitation, you are to experiment with the bit patterns used to represent ints in computers that use 2's complement to represent 32-bit integers. (See text, Section 4.2, pages 210-220. In C/C++ on Sun hardware the int type is a 32-bit 2's complement signed integer. Java uses the same representation on any hardare.)
Given either an "ordinary" integer (in decimal) or a bit pattern, it is easy to get the other representation, say, with programs like the following in C and in Java. The Java program uses another class to read the integer: GetData.java. Both the C and the Java use the Unix command line, rather than a development environment.
C Program | Java Program |
---|---|
/* integer_rep.c: Dec and Hex */ #include <stdio.h> #include <ctype.h> int main() { int i; char ch; for( ; ; ) { while (isspace(ch = getchar())) ; if (ch == 'x') { scanf("%x", &i); printf(" Dec: %10i\n", i); printf(" Hex: %08x \n", i); } else if (ch == 'i') { scanf("%i", &i); printf(" Dec: %10i\n", i); printf(" Hex: %08x \n", i); } else break; } } | // IntegerRep.java: Dec, Bin, and Hex public class IntegerRep { // main function to try out Base class public static void main (String[] args) { GetData data = new GetData(); while (true) { System.out.print(" Enter int ---> "); int n = data.getNextInt(); if (n == 0) break; String s = Integer.toBinaryString(n); /* to put in leading zeros */ while (s.length() < 32) s = "0" + s; String t = Integer.toHexString(n); while (t.length() < 8) t = "0" + t; System.out.println(" Dec: " + n); System.out.println(" Bin: " + s); System.out.println(" Hex: " + t); } } // end of main } |
C Run and Output | Java Run and Output |
% cc -o integer_rep integer_rep.c % integer_rep i 47 Dec: 47 Hex: 0000002f i -3 Dec: -3 Hex: fffffffd q % | % javac GetData.java % javac IntegerRep.java % java IntegerRep Enter int ---> 47 Dec: 47 Bin: 00000000000000000000000000101111 Hex: 0000002f Enter int ---> -3 Dec: -3 Bin: 11111111111111111111111111111101 Hex: fffffffd Enter int ---> 0 % |
As part of the recitation work, you must copy and execute both of these programs, recording the runs and results for the following input integers:
If you haven't had the advanced programming course and haven't done any C, run the C program anyway, using the commands in the table above. For the Java program, you can use the Unix-style commands or you may use the Borland JBuilder that many of you are accustomed to.
Here are more interesting programs that convert between number bases without using the C printf formatting or special Java library functions.
Base conversions: in C, in Java.
Contents of submission
for Recitation 2: Last Name, First Name; Course Number; Recitation Number (2).
|