APPFS
Advanced practical programming for scientists
 All Data Structures Files Functions Variables Typedefs Macros
ex1b2.c
Go to the documentation of this file.
1 
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <limits.h>
13 #include <string.h>
14 #include <assert.h>
15 
16 #define MAX_NUMS ((INT_MAX >> 5) + 1)
17 
18 
25 int main(void)
26 {
27  /* made static, because otherwise, the stack size might be too small.
28  */
29  static unsigned int have_num[MAX_NUMS];
30 
31  int n;
32  int total_nums = 0;
33 
34  /* we assume 32 bit integers, otherwise it will not work
35  */
36  assert(sizeof(int) == 4);
37 
38  memset(have_num, 0, sizeof(have_num)); // Proably uneccessary
39 
40  /* Read from file until data exhausted
41  */
42  while(fread(&n, sizeof(n), 1, stdin))
43  {
44  total_nums++;
45 
46  /* Check input: really >= 0 ? Otherwise ignore
47  */
48  if (n >= 0)
49  {
50  int idx = n >> 5; // n / 32
51  unsigned int msk = 1 << (n & 31); // bit number n mod 32
52 
53  assert(idx >= 0 && idx < MAX_NUMS);
54 
55  have_num[idx] |= msk;
56  }
57  }
58  if (!feof(stdin))
59  {
60  perror("fread: ");
61  exit(EXIT_FAILURE);
62  }
63 
64  fprintf(stderr, "Total numbers read = %d\n", total_nums);
65 
66  for(int i = 0; i < MAX_NUMS; i++)
67  if (have_num[i]) // just for speed up
68  for(int k = 0; k < 31; k++)
69  if (have_num[i] & (1 << k))
70  printf("%d\n", (i << 5) + k);
71 
72  return EXIT_SUCCESS;
73 }
int main(void)
Program to read binary positive 32 bit integers from stdin, sort the numbers and print them sorted...
Definition: ex1b2.c:25
#define MAX_NUMS
Maximum number of 32 bit ints we need to store bits.
Definition: ex1b2.c:16