fork(1) download
  1. #include <stdio.h>
  2. #include <limits.h>
  3.  
  4. static void reverse(char* buf, size_t size)
  5. {
  6. for (size_t i = 0; i < size/2; ++i) {
  7. // swap i <-> (size - i - 1)
  8. char temp = buf[i];
  9. buf[i] = buf[size - i - 1];
  10. buf[size - i - 1] = temp;
  11. }
  12. }
  13.  
  14.  
  15. static int to_binary_unsigned(unsigned int x, char* buf, size_t size)
  16. {
  17. if (!buf || size < 2)
  18. return -1; // error
  19.  
  20. buf[0] = '\0';
  21. size_t i = 1;
  22. for ( ; i < size; ++i) {
  23. buf[i] = "01"[x & 1];
  24. x >>= 1;
  25. if (x == 0)
  26. break;
  27. }
  28. if (i == size)
  29. return -1; // error
  30. reverse(buf, i + 1);
  31. return 0; // success
  32. }
  33.  
  34. static int to_binary(int x, char* buf, size_t size)
  35. {
  36. if (x < 0) {
  37. if (buf && size > 2)
  38. *buf = '-'; // write sign
  39. else
  40. return -1; // error
  41. return to_binary_unsigned(-(unsigned int)x, buf+1, size-1);
  42. }
  43. return to_binary_unsigned(x, buf, size);
  44. }
  45.  
  46.  
  47. int main(void)
  48. {
  49. int x;
  50. scanf("%d", &x);
  51. char buf[2 + CHAR_BIT * sizeof x]; // sign + null + binary digits
  52. to_binary(x, buf, sizeof buf);
  53. puts(buf);
  54. }
Success #stdin #stdout 0s 9416KB
stdin
-1
stdout
-1