0

I convert float to byte[] array with this code:

byte[] bytes = ByteBuffer.allocate(4).putFloat(number).array();

For example if I put the number 0.02f I get the bytes [60,-93,-41,10] Then I try to write this byte[] to file with this code:

FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
dbf.close();

On most platform in HEX-editor this file looks like this: 3C A3 D7 0A. But on special device same code gives this: 3C A3 D7 0D 0A. Before each 0A 0D appears.

I know than 0A is a LF and 0D 0A is a CRLF but I do not know how this can be.

With what it can be connected ?

1 Answers1

2

It sounds like when the data is transferred to your "special device" it is being translated as if it was a text file. This will corrupt the file in the manner you see. e.g. FTP has a text transfer mode which does this.

You shouldn't confuse text and binary. You are writing a binary format and if you read it as a binary format, new lines are not relevant.

Don't read it as text as it's not text and you won't have a problem.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    @VictorChurilov Still, Peter is right. Somewhere your file is being treated as if it is a text file instead of as a binary file. How are you sending it to the "special device"? Using FTP? Are you using binary transfer mode? Is there something else that treats the file as if it is a text file? – Jesper Apr 20 '17 at 07:58
  • That "Special device" (Android 6.0.1) generate that bad file with that simple code. Other devices use that code and genegate file without `0D` – Victor Churilov Apr 20 '17 at 08:01
  • @VictorChurilov Can you add `System.out.println("length= " + file.length());` immediately after writing in the code to confirm the file now has 5 bytes? (Assuming file is a `File`) – Peter Lawrey Apr 20 '17 at 08:06
  • This question is a simplification of the actual problems which can not solve by my colleague - http://stackoverflow.com/questions/43499255/fileoutputstream-write-non-existent-bytes ;I can add that `System.out.println` to real code. I need a few minutes. – Victor Churilov Apr 20 '17 at 08:18
  • `bytes` and `file` give same length – Victor Churilov Apr 20 '17 at 08:50
  • 1
    I found the trouble. The mail client breaks the file when sending. My bad. Thank you very much! – Victor Churilov Apr 20 '17 at 08:50