title: How to edit binary file in Android?
body: <p>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.</p>
  
  <p>This file that I want to open have multiple parameters written in 2 bytes. e.g. <code>00 06 00 50 01 AB = 6, 80, 427</code>
  So far I managed to open bin file, put all data from file into <code>byte[]</code>.</p>
  
  <p>Here is the code to open and read file:</p>
  
  <pre><code>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();
  }
  </code></pre>
  
  <p>Here is first attempt to convert <code>byte[]</code> into deciaml values:</p>
  
  <pre><code>for (int i = 0; i &lt; size / 2; i = i + 2) {
      intArray[i] = ((bytes[i] &amp; 0xff) &lt;&lt; 8) | (bytes[i + 1] &amp; 0xff);
  }
  </code></pre>
  
  <p>But in this code only every second value is correct. It's shows <code>6,0,80,0,1</code> and should be <code>6,80,1</code>.</p>
  
  <p>The second idea was to convert <code>byte[]</code> into <code>String[]</code> and then into e.g. <code>int[]</code> but It doesn't work as intended. In this fragment I didn't parse whole array, but only <code>hexArray[4]</code> which was <code>50</code> in hex and <code>80</code> in dec, but the result was <code>50</code>.</p>
  
  <pre><code>for (int i = 0; i &lt; size; i = i + 2) {
      num1 = String.format("%02X", bytes[i] &amp; 0xFF);
      num2 = String.format("%02X", bytes[i + 1] &amp; 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]));
  </code></pre>
  
  <p>I'm quite stuck here and need some guidance. I must say also that I'm new in programming.
  Thanks</p>