fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. char* __private_to_binary_representation(int n, char* print_here, int pos) {
  5. //printf("pos %d, n %d\n", pos, n);
  6. if (n == 0) {
  7. return print_here;
  8. }
  9. print_here = __private_to_binary_representation(n >> 1, print_here, pos + 1);
  10. (*print_here) = (n & 1) + '0';
  11. //printf("pos %d, n %d, n & 1 %d, *print_here %c\n", pos, n, n & 1, *print_here);
  12. return print_here + 1;
  13. }
  14.  
  15. char* to_binary_representation(int n, char* print_here) {
  16. int is_negative = n < 0? 1: 0;
  17. // primeiro, preencho o valor absoluto do número, então o primeiro bit sempre será 0
  18. char* null_terminator_pos = __private_to_binary_representation(abs(n), print_here + 1, 0);
  19. print_here[0] = '0';
  20.  
  21. // garantindo o final da string
  22. (*null_terminator_pos) = '\0';
  23.  
  24. if (is_negative) {
  25. char* bit_check;
  26. int bit1_found = 0;
  27. for (bit_check = null_terminator_pos - 1; bit_check >= print_here; bit_check--) {
  28. // troca os bits na representação de complemento de 2
  29. if (bit1_found) {
  30. (*bit_check) = (*bit_check) == '1'? '0': '1';
  31. } else if ((*bit_check) == '1') {
  32. bit1_found = 1;
  33. }
  34. }
  35. }
  36. return print_here;
  37. }
  38.  
  39. int main(void) {
  40. char buff[100];
  41. printf("to_binary_representation(%d), %s\n", 0, to_binary_representation(0, buff));
  42. printf("to_binary_representation(%d), %s\n", 1, to_binary_representation(1, buff));
  43. printf("to_binary_representation(%d), %s\n", 5, to_binary_representation(5, buff));
  44. printf("to_binary_representation(%d), %s\n", -5, to_binary_representation(-5, buff));
  45. printf("to_binary_representation(%d), %s\n", -1, to_binary_representation(-1, buff));
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 4460KB
stdin
Standard input is empty
stdout
to_binary_representation(0), 0
to_binary_representation(1), 01
to_binary_representation(5), 0101
to_binary_representation(-5), 1011
to_binary_representation(-1), 11