Ad

How To Edit Binary File In Android?

- 1 answer

I want to create an app that can open binary file, read and edit it's content in decimal values, and then save it back to binary file.

This file that I want to open have multiple parameters written in 2 bytes. e.g. 00 06 00 50 01 AB = 6, 80, 427 So far I managed to open bin file, put all data from file into byte[].

Here is the code to open and read file:

String path = getFilesDir().getAbsolutePath();
File file = new File(path + "/file.bin");
int size = (int) file.length();
byte[] bytes = new byte[size];

FileInputStream fis = new FileInputStream(file);
try {
    fis.read(bytes);
    ...
} finally {
    fis.close();
}

Here is first attempt to convert byte[] into deciaml values:

for (int i = 0; i < size / 2; i = i + 2) {
    intArray[i] = ((bytes[i] & 0xff) << 8) | (bytes[i + 1] & 0xff);
}

But in this code only every second value is correct. It's shows 6,0,80,0,1 and should be 6,80,1.

The second idea was to convert byte[] into String[] and then into e.g. int[] but It doesn't work as intended. In this fragment I didn't parse whole array, but only hexArray[4] which was 50 in hex and 80 in dec, but the result was 50.

for (int i = 0; i < size; i = i + 2) {
    num1 = String.format("%02X", bytes[i] & 0xFF);
    num2 = String.format("%02X", bytes[i + 1] & 0xFF);

    String twoByte = num1 + num2;
    hexArrayWithNull[i] = twoByte;
}
String[] hexArray = Arrays.stream(hexArrayWithNull).filter(Objects::nonNull).toArray(String[]::new);
num = String.format("%d", Integer.parseInt(hexArray[4]));

I'm quite stuck here and need some guidance. I must say also that I'm new in programming. Thanks

Ad

Answer

You increment i in each iteration by 2 and you store in intArray[i]. So, you store in index [0] then index [2] then index [4] and so on. This explains the zeros at odd indices [1], [3], ...

Also, you must continue the loop until size, not size/2.

Here is the correct loop:

for (int i = 0; i < size; i = i + 2) {
    intArray[i/2] = ((bytes[i] & 0xff) << 8) | (bytes[i + 1] & 0xff);
}

Here is the another possibility:

for (int i = 0; i < size/2; i = i + 1) {
    intArray[i] = ((bytes[2*i] & 0xff) << 8) | (bytes[2*i + 1] & 0xff);
}

[EDIT]

The reverse operation would be:

for (int i = 0; i < size/2; i = i + 1) {
    bytes[2*i] = (intArray[i] & 0xff00) / 256; //or >>8 instead of /256
    bytes[2*i+1] = intArray[i] & 0xff;
}
Ad
source: stackoverflow.com
Ad