I was trying to create a sort of compressing/decompressing algorithm and now that works I was thinking on how to write down to file its decompressed hex code. I tried to convert it in an array of byte but something strange happens:
the result file is bigger than the original one even if the decompressed hex string and the original one are equal. When I try to open it, it gives me Compatibility issue with current Windows version
To create the decompressed exe and so writing in it its hex code I used this code:
Any suggestions?FileOutputStream stream=new FileOutputStream("Hello2.exe"); stream.write(hex.getBytes()); stream.close();
The problem is that you're reading the bytes into a hex string, then writing the hex string directly to the file without converting it back to the appropriate bytes first.
Let's say the file contents are hello world
. As an array of bytes, this is {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64}
. After you read it into a string, you have "48656c6c6f20776F726C64"
. When you call getBytes()
on this string, you get the following byte array back: {0x34, 0x38, 0x36, 0x35, 0x36, 0x63, 0x36, 0x63, 0x36, 0x66, 0x32, 0x30, 0x37, 0x37, 0x36, 0x46, 0x37, 0x32, 0x36, 0x43, 0x36, 0x34}
. Thus, your output file is 48656c6c6f20776F726C64
, rather than hello world
.
This is because you're getting the byte representation of each individual character in the string, NOT the byte values of the hex pairs represented by the string.
See this question for a way to convert the string to bytes correctly: Convert a string representation of a hex dump to a byte array using Java?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments