CS 2734
Computer Organization II
For this laboratory, you are to experiment with the bit pattern used to represent an int 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.)
Given either an "ordinary" integer (in decimal) or a bit pattern, it is easy to get the other representation, say, with a simple program like the following:
#include <stdio.h>
#include <ctype.h>
void main(void){
int i;
char ch;
for( ; ; ) {
while (isspace(ch = getchar()))
;
if (ch == 'x') {
scanf("%x", &i);
printf(" Decimal: %10i\n", i);
printf(" Bits: %08x \n", i);
}
else if (ch == 'i') {
scanf("%i", &i);
printf(" Decimal: %10i\n", i);
printf(" Bits: %08x \n", i);
}
else break;
}
}
Typical output looks like the following (user input in boldface):
i 47 Decimal: 47 Bits: 0000002f i -3 Decimal: -3 Bits: fffffffd x ffffffff Decimal: -1 Bits: ffffffff qFor this laboratory, experiment with the program by entering various integers, including 0, 1, 2, -2, -3, 2147483647, 2147483648 (overflow), -2147483648, and -2147483649 (underflow).
/* writebase.c: convert between number bases in C
* This program does not handle bases > 10 nor
* does it handle negative numbers.
* Written by Neal R. Wagner, 7 Sept 1999
*/
#include <stdio.h>
#include <ctype.h>
void dumpout(int n, int base);
void writebase(int n, int base);
int readbase(int base);
void main(void)
{
int n, base;
for( ; ; ) {
printf("input base (in base 10)>>>");
base = readbase(10);
if (base <= 0) break;
printf("Input number (in base ");
writebase(base, 10);
printf(")>>>");
n = readbase(base);
dumpout(n, 10);
dumpout(n, 8);
dumpout(n, 2);
printf("--------------------------\n");
}
}
void dumpout(int n, int base)
{
printf("Base "); writebase(base, 10);
printf(": ");
writebase(n, base); putchar('\n');
}
void writebase(int n, int base)
{
if (n != 0) {
writebase(n/base, base);
putchar((n%base) + '0');
}
}
int readbase(int base)
{
char c;
int i = 0;
while (isdigit(c = getchar()))
i = base*i + (c - '0');
return i;
}
Here is some sample output:four06% writebase input base (in base 10)>>>8 Input number (in base 8)>>>23456 Base 10: 10030 Base 8: 23456 Base 2: 10011100101110 -------------------------- input base (in base 10)>>>10 Input number (in base 10)>>>99999 Base 10: 99999 Base 8: 303237 Base 2: 11000011010011111 -------------------------- input base (in base 10)>>>0