fork(2) download
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <string.h>
  4. #define str_size 32/4
  5. #define bin_size 32/8
  6.  
  7. void htob(char hex[], unsigned char bin[]);
  8.  
  9. /*That HEX is type of string converts to binary.*/
  10. int main(void)
  11. {
  12. char string[str_size+2] = "" ; //if string include 0x(0X) that array need +2
  13. unsigned char bin[bin_size] = "";
  14.  
  15. printf("請輸入欲轉換之字串:");
  16. scanf("%s", string);
  17.  
  18. htob(string, bin);
  19.  
  20. printf("MSB ");
  21. for (int i = bin_size-1; i >= 0; --i)
  22. {
  23. printf("%X ", bin[i]);
  24. }
  25. printf("LSB\n");
  26.  
  27. system("pause");
  28. return 0;
  29. }//這裡跳出 Run-Time Check Failure #2 - Stack around the variable 'string' was corrupted.
  30.  
  31. void htob(char hex[], unsigned char bin[])
  32. {
  33. enum HAVE {NO,YES=2};
  34. enum HAVE have_0x=NO;//or 0X
  35.  
  36. int b = bin_size - 1;
  37. int h = 0;
  38. int odd=0;//輸入基數個hex字元數
  39. int unfilled,temp, twice;
  40. unsigned char integer;
  41.  
  42. if (hex[h] == '0' && (hex[h + 1] == 'x' || hex[h + 1] == 'X'))//Whether have the input 0X/0x?
  43. have_0x = YES;
  44.  
  45. unfilled = str_size - (strlen(hex) - have_0x);
  46.  
  47. if (unfilled)
  48. {
  49. for (temp = 1; temp <= (unfilled / 2); ++temp,--b)//輸入未滿填則0
  50. {
  51. bin[b] = 0x00;
  52. }
  53. if (unfilled % 2)
  54. {
  55. odd = 1;
  56. }
  57. }
  58.  
  59. for (h=have_0x ; b>=0 && h<(int)strlen(hex) ; --b )
  60. {
  61. integer = 0x00;
  62. for (twice = 0; twice < 2;++twice)
  63. {
  64. if (hex[h] >= '0'&&hex[h] <= '9')
  65. {
  66. integer = integer * 16 + (hex[h] - '0');
  67. ++h;
  68. }
  69. else if (hex[h] >= 'a'&&hex[h] <= 'f')
  70. {
  71. integer = integer * 16 + (hex[h] - 'a'+10);
  72. ++h;
  73. }
  74. else if (hex[h] >= 'A'&&hex[h] <= 'F')
  75. {
  76. integer = integer * 16 + (hex[h] - 'A'+10);
  77. ++h;
  78. }
  79. else
  80. {
  81. printf("輸入非法hex字元\n");
  82. ++h;
  83. }
  84. if (odd)
  85. break;
  86. }
  87. bin[b] = integer;
  88. odd = 0;
  89. }
  90. }
  91.  
Success #stdin #stdout #stderr 0s 2160KB
stdin
0x12345678
stdout
請輸入欲轉換之字串:MSB  12  34  56  78  LSB
stderr
sh: 1: pause: not found