1
0

invert4.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* invert4.c -- using bit operations to display binary */
  2. #include <stdio.h>
  3. #include <limits.h>
  4. char * itobs(int, char *);
  5. void show_bstr(const char *);
  6. int invert_end(int num, int bits);
  7. int main(void)
  8. {
  9. char bin_str[CHAR_BIT * sizeof(int) + 1];
  10. int number;
  11. puts("Enter integers and see them in binary.");
  12. puts("Non-numeric input terminates program.");
  13. while (scanf("%d", &number) == 1)
  14. {
  15. itobs(number,bin_str);
  16. printf("%d is\n", number);
  17. show_bstr(bin_str);
  18. putchar('\n');
  19. number = invert_end(number, 4);
  20. printf("Inverting the last 4 bits gives\n");
  21. show_bstr(itobs(number,bin_str));
  22. putchar('\n');
  23. }
  24. puts("Bye!");
  25. return 0;
  26. }
  27. char * itobs(int n, char * ps)
  28. {
  29. int i;
  30. const static int size = CHAR_BIT * sizeof(int);
  31. for (i = size - 1; i >= 0; i--, n >>= 1)
  32. ps[i] = (01 & n) + '0';
  33. ps[size] = '\0';
  34. return ps;
  35. }
  36. /* show binary string in blocks of 4 */
  37. void show_bstr(const char * str)
  38. {
  39. int i = 0;
  40. while (str[i]) /* not the null character */
  41. {
  42. putchar(str[i]);
  43. if(++i % 4 == 0 && str[i])
  44. putchar(' ');
  45. }
  46. }
  47. int invert_end(int num, int bits)
  48. {
  49. int mask = 0;
  50. int bitval = 1;
  51. while (bits-- > 0)
  52. {
  53. mask |= bitval;
  54. bitval <<= 1;
  55. }
  56. return num ^ mask;
  57. }