I have an image in jpeg
format that I converted into a hex
string using an online tool. I copied that hex string and saved in a text file called imgHex.txt
. How can I convert the hex value inside imgHex.txt back to its original form (jpeg).
I tried to open imgHex.txt using "r"
parameter and then open a file test.jpeg
with the "wb"
parameter. And the write the contents of imgHex.txt to test.jpeg but with no success.
FILE* f;
FILE* img;
fopen_s(&f, "C:\\Users\\name\\Documents\\imgHex.txt", "r");
fopen_s(&img, "C:\\Users\\name\\Documents\\test.jpeg", "wb");
char b[512];
while (fgets(b, 512, f) != NULL)
{
fputs(b, img);
}
CodePudding user response:
Assuming that your imgHex.txt
DOES NOT start with 0x
but rather only consists of the hexadecimal digits, then this is a very simple operation. (If you file does start with 0x
, just skip past the first two bytes of the file).
First, you need to understand that each hexadecimal digit represents 4 bits, i.e. A = 1010
. This means you need to read two digits at a time so that you have one byte, i.e. A2 = 10100010
. Once you read each two digit pair, you convert this textual representation of a byte into its actual value. Then you just write that value into your output file. Repeat until you reach EOF for imgHex.txt
.
(Credits to @Weather Vane for actual code)
unsigned val;
while(fscanf(f, "%2x", &val) == 1) {
fputc(val, img)
}
This code succinctly reads two hexadecimal digits, "%2x"
from the file handle f
, and puts the resulting value into val
. It makes sure that one byte was read from f
, fscanf(...) == 1
, in order to make sure no errors occurred. Then it writes the single byte to the file handle img
, via fputc(val,img)
.
This will stop since once we reach the end of the imgHex.txt
file, fscanf(...)
will not return 1, but rather EOF (commonly this is -1, but depends on implementation).