I have a problem when I try to write String in a file. For example, I have this code to convert an Integer value to a 2-byte String but the String codification convert Integer to invisible bytes.
I need to convert, for example, 45557 integer number on 2 bytes 0xB1 and 0xF5 and convert it to String õ±. Then, in other processes, decoding õ± to get B1F5.
The problem is when I try decode õ±, I get C3B5C2B1. I know it is a problem of String codification but how can I solve it?
I'm trying this:
int iInteger = 45557;
int iLow = iInteger & 0b0000000011111111;
int iHight = (iInteger & 0b1111111100000000)>>8;
file_raw.open_file();
file_raw.println (" Character 1 num: " + iLow);
file_raw.println (" Character 2 num:" + iHight);
String cLow = new Character((char) 245).toString();
String cHigh = new Character((char) 177).toString();
Then the result is:
Character 1 num: 245
Character 2 num:177
Character 1 string: õ
Character 2 string :±
To your eyes they are good but when I am going to decode those characters to HEX I get 16-bit values because the coding is in UTF-8:
õ -> C3B5 (conversion on notepad++ or internet converters)
± -> C2B1
Just I want:
õ -> F5
± -> B1
You should work directly with raw byte arrays and avoid converting them to String in the middle, as String uses UTF-16 internally in Java, which causes encoding issues.
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ByteFileExample {
public static void main(String[] args) {
int iInteger = 45557;
byte iLow = (byte) (iInteger & 0xFF); // Low byte (F5)
byte iHigh = (byte) ((iInteger >> 8) & 0xFF); // High byte (B1)
try (FileOutputStream fos = new FileOutputStream("output.bin")) {
fos.write(iHigh); // Write the high byte (B1)
fos.write(iLow); // Write the low byte (F5)
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream("output.bin")) {
int high = fis.read(); // Read the high byte (B1)
int low = fis.read(); // Read the low byte (F5)
// Combine the two bytes into an integer
int result = (high << 8) | (low & 0xFF);
System.out.println("Decoded integer: " + result); // Output 45557
} catch (IOException e) {
e.printStackTrace();
}
}
}