aboutsummaryrefslogtreecommitdiff
path: root/lab1_datalab/ishow.c
blob: ffb1df7372505e22e091202b0a4d883700213981 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/* Display value of fixed point numbers */
#include <stdlib.h>
#include <stdio.h>

/* Extract hex/decimal/or float value from string */
static int get_num_val(char *sval, unsigned *valp) {
  char *endp;
  /* See if it's an integer or floating point */
  int ishex = 0;
  int isfloat = 0;
  int i;
  for (i = 0; sval[i]; i++) {
    switch (sval[i]) {
    case 'x':
    case 'X':
      ishex = 1;
      break;
    case 'e':
    case 'E':
      if (!ishex)
	isfloat = 1;
      break;
    case '.':
      isfloat = 1;
      break;
    default:
      break;
    }
  }
  if (isfloat) {
    return 0; /* Not supposed to have a float here */
  } else {
    long long int llval = strtoll(sval, &endp, 0);
    long long int upperbits = llval >> 31;
    /* will give -1 for negative, 0 or 1 for positive */
    if (valp && (upperbits == 0 || upperbits == -1 || upperbits == 1)) {
      *valp = (unsigned) llval;
      return 1;
    }
    return 0;
  }
}

void show_int(unsigned uf)
{
  printf("Hex = 0x%.8x,\tSigned = %d,\tUnsigned = %u\n",
	 uf, (int) uf, uf);
}


void usage(char *fname) {
  printf("Usage: %s val1 val2 ...\n", fname);
  printf("Values may be given in hex or decimal\n");
  exit(0);
}

int main(int argc, char *argv[])
{
  int i;
  unsigned uf;
  if (argc < 2)
    usage(argv[0]);
  for (i = 1; i < argc; i++) {
    char *sval = argv[i];
    if (get_num_val(sval, &uf)) {
      show_int(uf);
    } else {
      printf("Cannot convert '%s' to 32-bit number\n", sval);
    }
  }
  return 0;
}