Reading and writing a file in java in hexadecimal? - java

I'm having trouble finding what I'm looking for. Is there anyway to read a file by hexadecimal values in java, and to write another file? If I wanted to take one file and create a new file where every hexadecimal value was incremented, how would I do this? Like if I had a txt file that said "Hello" and I increment every hexadecimal value so that it should say "Ifmmp".
How do I read a file (any file, not just an ASCII text file) hexadecimal by hexadecimal, and write another file one hexadecimal at a time?

I believe this is what you're looking for...
Here's code to read from a file and take the hex values of each part in file.
/*
Code which defines a scanner class and FileInputStream
*/
String lineInFile = scannerName.nextLine();
int[] convertMeToHex = new int[lineInFile.length()];
for (int i = 0; i < convertMeToHex.length; i++)
convertMeToHex[i] = (int) lineInFile.charAt(i);
String[] hex = new String[convertMeToHex.length];
for (int i = 0; i < convertMeToHex.length; i++)
hex[i] = Integer.toHexString(convertMeToHex[i]));
You can convert hex back to int with int hexToInt = Integer.parseInt(hexNumber, 16);

Related

Converting a byte[] to a String in Java

Say we have a byte[] array:
byte[] data = {10,10,1,1,9,8}
and I want to convert these values in to a hexadecimal string:
String arrayToHex = "AA1198"
How can I do this? Using Java language in IntelliJ. Keep in mind this is my first semester of coding, so I'm already feeling lost.
First I start with this method:
public static String toHexString(byte[] data)
In the problem I'm trying to solve, we get a string from a user input, which is then converted to a byte[] array, and from there must be converted back into a string in hexadecimal format. But for simplification purposes I am just trying to input my own array.
So, here I have my array:
byte[] data = {10,10,1,1,9,8}
I know how to just print the byte array by just saying:
for (int i = 0; i < data.length; i++)
{
System.out.print(data[i]);
}
which will have an output of:
10101198
but obviously this is not what I'm looking for, as I have to convert the 10s to As, and I need a String type, not just an output. I'm sorry I'm so vague, but I'm truly lost and ready to give up!
This is not what you would normally do and would only work for byte values from 0 to 15.
byte[] data = {10,10,1,1,9,8};
StringBuilder sb = new StringBuilder();
for (byte b : data)
sb.append(Integer.toHexString(b));
String arrayAsHex = sb.toString();
What you would normally expect is "0A0A01010908" so that any byte value is possible.
String arrayAsHex = DatatypeConverter.printHexBinary(data);

String of 0's and 1's to File as bits

I am working on a Huffman java application and i'm almost done. I have one problem though. I need to save a String of something like: "101011101010" to a file. When I save it with my current code it saves it as characters which take up 1 byte every 0 or 1. I'm pretty sure it's possible to save every 0/1 as a bit.
I already tried some things with BitSet and Integer.valueOf but I can't get them to work. This is my current code:
FileOutputStream fos = new FileOutputStream("encoded.bin");
fos.write(encoded.getBytes());
fos.close();
Where 'encoded' is a String which can be like: "0101011101".
If I try to save it as integer the leading 0 will be removed.
Thanks in advance!
EDIT: Huffman is a compression method so the outputted file should be as small as possible.
I think I found my answer. I put the 1's and 0's in a BitSet using the following code:
BitSet bitSet = new BitSet(encoded.length());
int bitcounter = 0;
for(Character c : encoded.toCharArray()) {
if(c.equals('1')) {
bitSet.set(bitcounter);
}
bitcounter++;
}
After that I save it to the file using bitSet.toByteArray()
When I want to read it again I convert it back to a bitset using BitSet.valueOf(bitSet.toByteArray()). Then I loop through the bitset like this:
String binaryString = "";
for(int i = 0; i <= set.length(); i++) {
if(set.get(i)) {
binaryString += "1";
} else {
binaryString += "0";
}
}
Thanks to everyone who helped me.
Binary files are limited to storing bits in multiples of eight. You can solve this problem by chopping the string into eight-bit chunks, converting them to bytes using Byte.parseByte(eightCharString, 2) and adding them to a byte array:
Compute the length of the byte array by dividing the length of your bit string by eight
Allocate an array of bytes of the desired length
Run a loop that takes substrings from the string at positions representing multiples of eight
Parse each chunk, and put the result into the corresponding byte
Call fos.write() on the byte array
Try this.
String encoded = "0101011101";
FileOutputStream fos = new FileOutputStream("encoded.bin");
String s = encoded + "00000000".substring(encoded.length() % 8);
for (int i = 0, len = s.length(); i < len; i += 8)
fos.write((byte)Integer.parseInt(s.substring(i, i + 8), 2));
fos.close();

Save a hex String to File.hex in java

I have a String which contains hex values. Now i want to write this exact string to a file with the ending .hex . How can i realize this in java?
I already tried to convert the Hex Values into ASCII and then write this string into a file.
But all Hex Values which are higher then 127(dec) can't be processed correctly.
86(hex) is transformed to ?(char), which is 3F(hex) and not 86(hex).
You can try to take each char of your string, convert it to integer and then write values in bytes in a file. To do the opposite process, you just have to read the file into a byte array and convert each byte into a char to retrieve your string. Then I'm sure you can find some algorithm to cast your string into Hex string.
For me the Answer was this:
Under Projectproperties i needed to set the Text-file-Encoding to ISO-8859-1.
Then my old procedure worked very well.
public static String hexToASCII(String hex){
if(hex.length()%2 != 0){
System.err.println("requires EVEN number of chars");
return null;
}
StringBuilder sb = new StringBuilder();
for( int i=0; i < hex.length()-1; i+=2 ){
String output = hex.substring(i, (i + 2));
int decimal = Integer.parseInt(output, 16);
sb.append((char)decimal);
}
return sb.toString();
}

JAVA - Write binary number to a file and read it

How can i write to a file a binary number without it to cut the zeros .
I'm writing like this :
byte[] b = new BigInteger("1011010101010110", 2).toByteArray();
FileOutputStream fos = new FileOutputStream("file",true);
fos.write(b);
But then for example : When i write 0000001, it writes in the file just 1 and ignores the zeros, the same happens if i write 001001001000 , it ignores the zeros on the left reading 8bits at the time from the right to the left.
What is the correct way to write binary digits to a file ? If this is the correct way, i'm might be trying to read the file in the wrong way ( I'm using the read() of InputStream )
Ps-(8 digits must be 1 byte so writing as a string is not an option, cause each digit is 1 byte.)
You can try something like this
String s = "0000001";
byte[] a = new byte[s.length()];
for (int i = 0; i < s.length(); i++) {
a[i] = (byte) (s.charAt(i) & 1);
}
You don't want to write it as a binary, you want to write it as a String representing the binary. The problem is that Java has no way to know you want it padded. I would suggest converting your binary numbers to a String, then left-padding with 0 (Apache StringUtils will help with this)

How to convert 1s and 0s to String?

Please have a look at the following machine code
‎0111001101110100011100100110010101110011011100110110010101100100
This means something. I need to convert this to string. When I use Integer.parseInt() with the above as the string and 2 as the radix(to convert it to bytes), it gives number format exception.
And I believe I have to seperate this into sets of 8 pieces (like ‎01110011 , 10111010, etc). Am I correct?
Please help me to convert this correctly to string.
Thanks
final String s =
"0111001101110100011100100110010101110011011100110110010101100100";
final StringBuilder b = new StringBuilder();
for (int i = 0; i < s.length(); i+=8)
b.append((char)Integer.parseInt(s.substring(i,i+8),2));
System.out.println(b);
prints "stressed"
A shorter way of reading large integers is to use BigInteger
final String s = "0111001101110100011100100110010101110011011100110110010101100100";
System.out.println(new String(new BigInteger('0'+s, 2).toByteArray(), 0));
prints
stressed
It depends on the encoding of the String.
An ASCII coded string uses 1 byte for each character while a unicode coded string takes 2 bytes for each character. There are many other types of encodings. The binary layout differs for each encoding.
So you need to find the encoding that was used to write this string to binary format

Categories