#include #include #include /* given 8 bits of 0 or 1 on the command line, will interpret them in unsigned, signed, one's compliment, two's complement and excess 128 */ int bits_unsigned (char **bits)//working { int currentval; //the current value int currentpower; //the current power of 2 int bitsplace; //holds the position where we are in the bits array int bitval; //either 0 or 1 currentval = 0; for (bitsplace = 8, currentpower = 0 ; bitsplace >= 1; bitsplace--, currentpower++) { bitval = atoi(bits[bitsplace]); currentval = (currentval + (bitval * pow(2,currentpower))); } return currentval; } int bits_signed (char **bits) //working { int currentval; //the current value int currentpower; //the current power of 2 int bitsplace; //holds the position where we are in the bits array int bitval; //either 0 or 1 currentval = 0; for (bitsplace = 8, currentpower = 0 ; bitsplace >= 2; bitsplace--, currentpower++) { bitval = atoi(bits[bitsplace]); currentval = (currentval + (bitval * pow(2,currentpower))); } if (atoi(bits[1]) == 1) //if it is signed to be nevative currentval = (currentval * -1); return currentval; } int bits_unsigned_2 (char *bits) //given an array NOT from the command line { int currentval; //the current value int currentpower; //the current power of 2 int bitsplace; //holds the position where we are in the bits array int bitval; //either 0 or 1 currentval = 0; for (bitsplace = 7, currentpower = 0 ; bitsplace >= 0; bitsplace--, currentpower++) { bitval = bits[bitsplace]; currentval = (currentval + (bitval * pow(2,currentpower))); } return currentval; } int bits_ones_complement (char **bits) { char newbits[8] = {0}; //creates a new array of character strings int bitsplace; //holds the value in bits int currentval; // if (atoi(bits[1]) == 0) currentval = bits_signed(bits); else { for (bitsplace = 8; bitsplace >= 1; bitsplace--) if (atoi(bits[bitsplace]) == 0) newbits[bitsplace - 1] = 1; currentval = (bits_unsigned_2(newbits) * -1); } return currentval; } int bits_twos_complement (char **bits) { char newbits[8] = {0}; //creates a new array of character strings int bitsplace; //holds the value in bits int currentval; // if (atoi(bits[1]) == 0) currentval = bits_signed(bits); else { for (bitsplace = 8; bitsplace >= 1; bitsplace--) if (atoi(bits[bitsplace]) == 0) newbits[bitsplace - 1] = 1; if (newbits[8] == 0) newbits[8] = 1; else newbits[8] = 0; currentval = (bits_unsigned_2(newbits) * -1); } return currentval; } int bits_excess_128 (char **bits) //working { int currentval; currentval = (bits_unsigned(bits) - 128); return currentval; } int main (int count, char **bits) { printf("Unsigned: %d\n", bits_unsigned(bits)); printf("Signed magnitude: %d\n", bits_signed(bits)); printf("One's complement: %d\n", bits_ones_complement(bits)); printf("Two's complement: %d\n", bits_twos_complement(bits)); printf("Excess 128: %d\n", bits_excess_128(bits)); return 0; }