Guest User

Untitled

a guest
Jan 17th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. ///
  2. /// input hex string then convert to binary string output as file
  3. ///
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8.  
  9. int main(int argc, char* argv[])
  10. {
  11. // get input hex string to convert to binary
  12. if (argc != 2)
  13. {
  14. printf("Usage: hextobin <input-hexstring>\n");
  15. return -1;
  16. }
  17.  
  18. // get input hex string
  19. char* hexstring = argv[1];
  20. char* hexstr_ptr = hexstring;
  21.  
  22. // find string length
  23. int len = strlen(hexstring);
  24. // form hex string
  25. char temp_hexstr[4+1];
  26. memset(temp_hexstr, 0, sizeof(temp_hexstr));
  27.  
  28. // result file content is half of the input string's length
  29. unsigned char bytes_result[len / 2];
  30.  
  31. // result index to store result back to our array
  32. int ri = 0;
  33. // loop through each byte in hexstring
  34. for (int i=0; i<len; i+=2)
  35. {
  36. // form hexstring
  37. strncpy(temp_hexstr+2, hexstr_ptr, 2);
  38. // prefix with 0x
  39. temp_hexstr[0] = '0';
  40. temp_hexstr[1] = 'x';
  41. // proceed hexstring pointer
  42. hexstr_ptr += 2;
  43.  
  44. // convert hexstring to value
  45. unsigned char byte = strtol(temp_hexstr, NULL, 0);
  46. // store result in our result array
  47. bytes_result[ri++] = byte;
  48.  
  49. //printf("%s => 0x%X\n", temp_hexstr, byte);
  50.  
  51. // zero out temp hexstr
  52. memset(temp_hexstr, 0, sizeof(temp_hexstr));
  53. }
  54.  
  55. //for (int i=0; i<ri; i++)
  56. //{
  57. // printf("bytes_result[%i] = 0x%X\n", i, bytes_result[i]);
  58. //}
  59.  
  60. // open file for writing
  61. FILE* file = fopen("output.txt", "wb");
  62. if (file == NULL)
  63. {
  64. printf("Cannot open file for writing");
  65. return -1;
  66. }
  67.  
  68. // write all at once to result file
  69. int result_obj_written = 0;
  70. result_obj_written = fwrite(bytes_result, sizeof(bytes_result), 1, file);
  71.  
  72. if (result_obj_written != 1)
  73. {
  74. printf("Something wrong in writing the file");
  75.  
  76. // close the file
  77. fclose(file);
  78. file = NULL;
  79. return -1;
  80. }
  81.  
  82. // close the file
  83. fclose(file);
  84. file = NULL;
  85.  
  86. return 0;
  87. }
Add Comment
Please, Sign In to add comment