/* EXERCISE 2-9 */ /* FOR BOTH POSITIVE AND NEGATIVE NUMBERS, x -= 1 REPLACES THE */ /* RIGHTMOST 1 BIT WITH A 0 BIT AND PROPAGATES 1 BITS RIGHTWARD. */ /* POSITIVE: x = 0011 1000, x-1 = 0011 0111 */ /* NEGATIVE: x = 1011 1000 = -(0100 1000) ADD THIS TO OVERFLOW */ /* x-1 = 1011 0111 = -(0100 1001) */ /* SINCE THE PROPAGATED RIGHT 1 BITS IN x-1 MATCH 0 BITS IN x, */ /* x &= (x-1) DELETES THE RIGHTMOST BIT IN x. */ #include <stdio.h> #define MAXLEN 5 /* FOR AN ARRAY OF 4 HEX DIGITS + '\0'. */ int loadstr(char s[]); unsigned int htou(char s[]); int bitcount(unsigned x); int error; char string_1[MAXLEN]; enum boolean {NO, YES}; enum escapes {BELL = '\a', BACKSPACE = '\b', TAB = '\t', NEWLINE = '\n', VTAB = '\v', RETURN = '\r'}; main() { int len, count; unsigned int uns1; /* LOAD A STRING FROM THE INPUT LINE */ len = loadstr(string_1); if (error == NO) if (len == 0) printf("STRING IS MISSING\n"); else { uns1 = htou(string_1); if (error == NO) printf("BIT COUNT = %d\n", bitcount(uns1)); } printf("\nEND OF PROGRAM\n"); return 0; } /* LOADSTR: LOAD THE NEXT NON-BLANK STRING FROM THE INPUT LINE */ int loadstr(char s[]) { int c = 0; int i = 0; int end_string = NO; error = NO; if (c != '\n' && c != EOF) { while (error == NO && end_string == NO && (c = getchar()) != NEWLINE && c != EOF) if (c == ' ' || c == BELL || c == BACKSPACE || c == TAB || c == VTAB || c == RETURN) if (i > 0) end_string = YES; else ; else if (i < MAXLEN - 1) { s[i++] = c; } else { error = YES; printf("\nSTRING IS TOO LONG\n"); } s[i] = '\0'; } return i; } /* HTOU: CONVERT A STRING OF HEX DIGITS TO AN UNSIGNED INTEGER */ unsigned int htou(char s[]) { unsigned int dec = 0; int i = 0; int n; if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) i = 2; while (error == NO && s[i] != '\0') { if (s[i] >= '0' && s[i] <= '9') n = s[i] - '0'; else if (s[i] >= 'a' && s[i] <= 'f') n = 10 + s[i] - 'a'; else if (s[i] >= 'A' && s[i] <= 'F') n = 10 + s[i] - 'A'; else { error = YES; printf("\nINVALID HEX NUMBER\n"); } if (error == NO) dec = 16 * dec + n; ++i; } return dec; } /* BITCOUNT: COUNT THE 1 BITS IN x. */ int bitcount(unsigned x) { int b; for (b = 0; x != 0; x &= (x - 1)) b++; return b; }