fork(1) download
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. // Print binary number represented as boolean array.
  7. // the most significant bits go first in the output
  8. void print_bin(bool *bits, int nbits) {
  9. for(int i = nbits; i-->0; ) {
  10. putchar("01"[bits[i]]);
  11. if (i % 8 == 0)
  12. putchar(' ');
  13. }
  14. putchar('\n');
  15. }
  16.  
  17. // Convert an integer to binary representation as boolean array.
  18. // the least significant bit is at the start (index 0) of the array
  19. void ull_to_bin(unsigned long long n, bool *bits, int nbits) {
  20. for(int i = 0; i < nbits; i++)
  21. bits[i] = (n >> i) & 1; //store the ith bit in b[i]
  22. }
  23.  
  24. // Read line from `stream`.
  25. // fail if input line is too long (larger than maxsize)
  26. // return -1 on error
  27. // return size of the line (including trailing '\0') on success
  28. int readline(FILE* stream, char *line, int maxsize) {
  29. char *s = fgets(line, maxsize, stream);
  30. if (s == NULL) return -1; // can't read
  31.  
  32. int size = strlen(s) + 1;
  33. if (size == maxsize && s[maxsize-2] != '\n') return -1; // line is too long
  34.  
  35. return size;
  36. }
  37.  
  38. int main() {
  39. FILE* fp = stdin; // read input from stdin
  40. const size_t maxline = 38; // 16 + 4 + 16 + \n\0
  41. char line[maxline];
  42. size_t lineno = 1;
  43. for (; readline(fp, line, maxline) > 0; ++lineno) {
  44. // read pair of numbers
  45. unsigned long long x, y;
  46. if (sscanf(line, "%llx %llx", &x, &y) != 2) { //NOTE: it ignores some input
  47. fprintf(stderr, "error: can't parse line #%zd: '%s'\n", lineno, line);
  48. exit(EXIT_FAILURE);
  49. }
  50.  
  51. // convert to binary representation and print it
  52. const int nbits = 8 * sizeof(unsigned long long);
  53. bool bits[nbits];
  54. ull_to_bin(x, bits, nbits);
  55. print_bin(bits, nbits);
  56. ull_to_bin(y, bits, nbits);
  57. print_bin(bits, nbits);
  58. puts("");
  59. }
  60. if (!feof(fp)) {
  61. fprintf(stderr, "error: line #%zd: not all input is read\n", lineno);
  62. exit(EXIT_FAILURE);
  63. }
  64. }
Success #stdin #stdout 0.01s 1724KB
stdin
0000000000000000    0000000000000000
FFFFFFFFFFFFFFFF    FFFFFFFFFFFFFFFF
3000000000000000    1000000000000001
stdout
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 
00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 

11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 
11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 

00110000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 
00010000 00000000 00000000 00000000 00000000 00000000 00000000 00000001