1

I am trying to convert long to bytes because I want to write the time stamp in seconds in a file. Belwo are the method wich I am using to convert long to bytes[] and how I write them into a file..

What I am getting from the following line:

bos.write( ( CSysUtils.longToBytes(CSysUtils.getTSMilli()) ) );

is an unreadable code/format:

code:

public static long getTSSec() {
    Log.w(TAG, CSubTag.bullet("getTSSec"));

    return System.currentTimeMillis()/1000;
}

public static byte[] longToBytes(long l) {
    byte[] result = new byte[8];
    for (int i = 7; i >= 0; i--) {
        result[i] = (byte)(l & 0xFF);
        l >>= 8;
    }
    return result;
}

write to a file:

fos = new FileOutputStream(file, true);
bos = new BufferedOutputStream(fos);

bos.write( ( CSysUtils.longToBytes(CSysUtils.getTSSec()) ) );
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • 3
    What do you mean "unreadable"? That you can't read it? That your code can't read it back again? – Andy Turner Nov 25 '15 at 13:22
  • 1
    use these methods here http://stackoverflow.com/questions/4485128/how-do-i-convert-long-to-byte-and-back-in-java – thumbmunkeys Nov 25 '15 at 13:23
  • Is not easier to write it in ascii as a String? – Nanoc Nov 25 '15 at 13:24
  • Why do you want to write them to file as bytes[]? Why not as String. – Raf Nov 25 '15 at 13:24
  • @Raf because iin the end i need to convert it to bytes..for an example if i want to erite "s" to a file it should be written as follows: "s".getbytes – Amrmsmb Nov 25 '15 at 13:25
  • did you try `java.io.DataInput` and `java.io.DataOutput` or `java.io.RandomAccessFile` which implements them both? – pskink Nov 25 '15 at 13:33
  • 2
    Confusing. You don't even specify the expected format of the output file. For instance, do you expect your longs to be stored in big endian format, little endian? – fge Nov 25 '15 at 13:33
  • In Java, all numeric primitives (including `byte`) are *signed*. Maybe that is confusing things when you look at the data? I just tested your loop, and it works. – dsh Nov 25 '15 at 18:35

1 Answers1

0

You can´t do this?:

bos.write(Long.toString(CSysUtils.getTSSec()).getBytes());

With this, the milliseconds are human readable in the output file.

Is that what you need?

Francisco Hernandez
  • 2,378
  • 14
  • 18