I have some files i would like to convert to hex, alter, and then reverse again, but i have a problem trying to do jars, zips, and rars. It seems to only work on files containing normally readable text. I have looked all around but cant find anything that would allow jars or bats to do this correctly. Does anyone have an answer that does both? converts to hex then back again, not just to hex?
Asked
Active
Viewed 4,988 times
2 Answers
5
You can convert any file to hex. It's just a matter of obtaining a byte stream, and mapping every byte to two hexadecimal numbers.
Here's a utility class that lets you convert from a binary stream to a hex stream and back:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
public class Hex {
public static void binaryToHex(InputStream is, OutputStream os) {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
try {
int value;
while ((value = is.read()) != -1) {
writer.write(String.format("%02X", value));
}
writer.flush();
} catch (IOException e) {
System.err.println("An error occurred");
}
}
public static void hexToBinary(InputStream is, OutputStream os) {
Reader reader = new BufferedReader(new InputStreamReader(is));
try {
char buffer[] = new char[2];
while (reader.read(buffer) != -1) {
os.write((Character.digit(buffer[0], 16) << 4)
+ Character.digit(buffer[1], 16));
}
} catch (IOException e) {
System.err.println("An error occurred");
}
}
}
Partly inspired by this sample from Mykong and this answer.

Community
- 1
- 1

Robby Cornelissen
- 91,784
- 22
- 134
- 156
-
1This is correct. +1... But note that you will corrupt almost all non-text files by altering random bytes. – Codebender Aug 24 '15 at 03:37
-
@Robby Cornelissen this code i have tried but enter was converted to .. and this doesn't help me convert it back. – Moocow9m Aug 24 '15 at 03:40
-
@Robby, the OP wants to convert to hex, **alter** and convert it back. – Codebender Aug 24 '15 at 03:41
-
@Moocow9m The example code has hex and text output. You only need the hex output. – Robby Cornelissen Aug 24 '15 at 03:41
-
-
@RobbyCornelissen it doesn't convert it back... I need it to convert back on command. – Moocow9m Aug 24 '15 at 03:43
-
@RobbyCornelissen how do i get rid of the original text in the output? – Moocow9m Aug 24 '15 at 04:05
-
@RobbyCornelissen it seems on conversion back i get an exception...http://prntscr.com/886l51 – Moocow9m Aug 24 '15 at 04:12
-
Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/87733/discussion-between-moocow9m-and-robby-cornelissen). – Moocow9m Aug 24 '15 at 04:12
1
Don't use a Reader
to read String
/ char
/ char[]
, use an InputStream
to read byte
/ byte[]
.

Andreas
- 154,647
- 11
- 152
- 247