Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///
- /// input hex string then convert to binary string output as file
- ///
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- int main(int argc, char* argv[])
- {
- // get input hex string to convert to binary
- if (argc != 2)
- {
- printf("Usage: hextobin <input-hexstring>\n");
- return -1;
- }
- // get input hex string
- char* hexstring = argv[1];
- char* hexstr_ptr = hexstring;
- // find string length
- int len = strlen(hexstring);
- // form hex string
- char temp_hexstr[4+1];
- memset(temp_hexstr, 0, sizeof(temp_hexstr));
- // result file content is half of the input string's length
- unsigned char bytes_result[len / 2];
- // result index to store result back to our array
- int ri = 0;
- // loop through each byte in hexstring
- for (int i=0; i<len; i+=2)
- {
- // form hexstring
- strncpy(temp_hexstr+2, hexstr_ptr, 2);
- // prefix with 0x
- temp_hexstr[0] = '0';
- temp_hexstr[1] = 'x';
- // proceed hexstring pointer
- hexstr_ptr += 2;
- // convert hexstring to value
- unsigned char byte = strtol(temp_hexstr, NULL, 0);
- // store result in our result array
- bytes_result[ri++] = byte;
- //printf("%s => 0x%X\n", temp_hexstr, byte);
- // zero out temp hexstr
- memset(temp_hexstr, 0, sizeof(temp_hexstr));
- }
- //for (int i=0; i<ri; i++)
- //{
- // printf("bytes_result[%i] = 0x%X\n", i, bytes_result[i]);
- //}
- // open file for writing
- FILE* file = fopen("output.txt", "wb");
- if (file == NULL)
- {
- printf("Cannot open file for writing");
- return -1;
- }
- // write all at once to result file
- int result_obj_written = 0;
- result_obj_written = fwrite(bytes_result, sizeof(bytes_result), 1, file);
- if (result_obj_written != 1)
- {
- printf("Something wrong in writing the file");
- // close the file
- fclose(file);
- file = NULL;
- return -1;
- }
- // close the file
- fclose(file);
- file = NULL;
- return 0;
- }
Add Comment
Please, Sign In to add comment