Question: Write a program in C that that converts a given bit string (up to 32-bits) into decimal assuming the input is given in unsigned magnitude

Write a program in C that that converts a given bit string (up to 32-bits) into decimal assuming the input is given in unsigned magnitude and two's complement.

1. You must read each bit in from the user one char at a time using the function getchar, which returns a char. Hint: in order to convert a char to an int, subtract the character 0 from the former.

2. Do the conversions as efficiently as possible, e.g., avoid calling any kind of pow function or even doing multiplication-by-2 with the * operator. Instead, use bitwise operations.

starting point:

#include #define MAX_BITS 32

int main() {

char array[MAX_BITS];//declaring char array to read string of bits

int i=0; printf("Enter up to 32 bits (hit 'enter' to terminate early): ");

while(1) {

char bit = getchar(); // reads the first bit (as a char) if(bit==' ')break;//if a line entered then breaking loop array[i++]=bit;//assigning to array }

array[i]='\0';

//displaying output printf("String entered: %s",array); return 0; }

example Final output:

Enter up to 32 bits (hit 'enter' to terminate early): 1011

Unsigned magnitude: 11

Twos complement: -5

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!