fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void BinFormat(unsigned short character, char *text) {
  5. text[16] = '\0'; // Define o final da string corretamente
  6. for (int i = 15; i >= 0; i--) // Iterar sobre 16 bits
  7. text[i] = ((character >> (15 - i)) & 1) + '0';
  8. }
  9.  
  10. int main(void) {
  11. char *text = malloc(17); // Alocar espaço para 16 bits + '\0'
  12. if (!text) return 1; // Verificar erro na alocação
  13.  
  14. BinFormat(1, text);
  15. printf("%s\n", text); // Deve imprimir: "0000000000000001"
  16.  
  17. BinFormat(2, text);
  18. printf("%s\n", text); // Deve imprimir: "0000000000000010"
  19.  
  20. BinFormat(3, text);
  21. printf("%s\n", text); // Deve imprimir: "0000000000000011"
  22.  
  23. BinFormat(65535, text);
  24. printf("%s\n", text); // Deve imprimir: "1111111111111111"
  25.  
  26. free(text); // Liberar memória
  27. return 0;
  28. }
Success #stdin #stdout 0s 5292KB
stdin
Standard input is empty
stdout
0000000000000001
0000000000000010
0000000000000011
1111111111111111