Guest User

Untitled

a guest
Feb 18th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.45 KB | None | 0 0
  1. #include "stdio.h"
  2. #include "math.h"
  3. #include <string.h>
  4.  
  5. int hex2dec(char * hex);
  6. int check_32bit(char *input);
  7. int main(){
  8. int str_len = 8;
  9. char input[str_len];
  10. printf("Please enter a hexadecimal value:");
  11. scanf("%s",input);
  12.  
  13. if (check_32bit(input) == 0){
  14. printf("The decimal value of %s is %d\n",input,hex2dec(input));
  15. }
  16. else{
  17. printf("Sorry, We only handle 32 bit values :(\n");
  18. }
  19.  
  20.  
  21.  
  22. return 0;
  23. }
  24. int check_32bit(char *input){
  25. if (strlen(input) <= 8){
  26. return 0;
  27. }
  28. else{
  29. return -1;
  30. }
  31. }
  32. int hex2dec(char * hex)
  33. {
  34. //char hex[N];
  35. int length = strlen(hex);
  36. int i,j,n[length];
  37. int dec=0;
  38. for(i=0;i<length;i++)
  39. {
  40. switch(hex[i])
  41. {
  42. case '0':
  43. n[i]=hex[i]-48; //Ascii code of 0 is 48 48-48=0//
  44. break;
  45. case '1':
  46. n[i]=hex[i]-48; //Ascii code of 1 is 49 49-48=1//
  47. break;
  48. case '2':
  49. n[i]=hex[i]-48; //Ascii code of 2 is 50 50-48=2//
  50. break;
  51. case '3':
  52. n[i]=hex[i]-48; //Ascii code of 3 is 51 51-48=3//
  53. break;
  54. case '4':
  55. n[i]=hex[i]-48; //Ascii code of 4 is 52 52-48=4//
  56. break;
  57. case '5':
  58. n[i]=hex[i]-48; //Ascii code of 5 is 53 53-48=5//
  59. break;
  60. case '6':
  61. n[i]=hex[i]-48; //Ascii code of 6 is 54 54-48=6//
  62. break;
  63. case '7':
  64. n[i]=hex[i]-48; //Ascii code of 7 is 55 55-48=7//
  65. break;
  66. case '8':
  67. n[i]=hex[i]-48; //Ascii code of 8 is 56 56-48=8//
  68. break;
  69. case '9':
  70. n[i]=hex[i]-48; //Ascii code of 9 is 57 57-48=9//
  71. break;
  72. case 'A':
  73. n[i]=hex[i]-55; //Ascii code of A is 65 65-55=10//
  74. break;
  75. case 'B':
  76. n[i]=hex[i]-55; //Ascii code of B is 65 66-55=11//
  77. break;
  78. case 'C':
  79. n[i]=hex[i]-55; //Ascii code of C is 65 67-55=12//
  80. break;
  81. case 'D':
  82. n[i]=hex[i]-55; //Ascii code of D is 65 68-55=13//
  83. break;
  84. case 'E':
  85. n[i]=hex[i]-55; //Ascii code of E is 65 68-55=14//
  86. break;
  87. case 'F':
  88. n[i]=hex[i]-55; //Ascii code of F is 65 69-55=15//
  89. break;
  90. }
  91. }
  92. for(i=0,j=length;i<length;i++,j--)
  93. dec=dec+(n[j-1]*pow(16,i));
  94. return dec;
  95. }
Add Comment
Please, Sign In to add comment