You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 regels
1.5 KiB

1 jaar geleden
  1. /* Display value of fixed point numbers */
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. /* Extract hex/decimal/or float value from string */
  5. static int get_num_val(char *sval, unsigned *valp) {
  6. char *endp;
  7. /* See if it's an integer or floating point */
  8. int ishex = 0;
  9. int isfloat = 0;
  10. int i;
  11. for (i = 0; sval[i]; i++) {
  12. switch (sval[i]) {
  13. case 'x':
  14. case 'X':
  15. ishex = 1;
  16. break;
  17. case 'e':
  18. case 'E':
  19. if (!ishex)
  20. isfloat = 1;
  21. break;
  22. case '.':
  23. isfloat = 1;
  24. break;
  25. default:
  26. break;
  27. }
  28. }
  29. if (isfloat) {
  30. return 0; /* Not supposed to have a float here */
  31. } else {
  32. long long int llval = strtoll(sval, &endp, 0);
  33. long long int upperbits = llval >> 31;
  34. /* will give -1 for negative, 0 or 1 for positive */
  35. if (valp && (upperbits == 0 || upperbits == -1 || upperbits == 1)) {
  36. *valp = (unsigned) llval;
  37. return 1;
  38. }
  39. return 0;
  40. }
  41. }
  42. void show_int(unsigned uf)
  43. {
  44. printf("Hex = 0x%.8x,\tSigned = %d,\tUnsigned = %u\n",
  45. uf, (int) uf, uf);
  46. }
  47. void usage(char *fname) {
  48. printf("Usage: %s val1 val2 ...\n", fname);
  49. printf("Values may be given in hex or decimal\n");
  50. exit(0);
  51. }
  52. int main(int argc, char *argv[])
  53. {
  54. int i;
  55. unsigned uf;
  56. if (argc < 2)
  57. usage(argv[0]);
  58. for (i = 1; i < argc; i++) {
  59. char *sval = argv[i];
  60. if (get_num_val(sval, &uf)) {
  61. show_int(uf);
  62. } else {
  63. printf("Cannot convert '%s' to 32-bit number\n", sval);
  64. }
  65. }
  66. return 0;
  67. }