binbit.c 1.0 KB

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