javaalgorithmbyteshortbcd

Convert short number to byte array java


my purpose to read from stream as byte per digit do some logic and write back to binary file

Lets say the representation of data is 0F000200 17000000 07003B00

so we have method to represent it

   InputStream stream = new FileInputStream(args[0]);

    private static int readShort(InputStream stream) throws IOException {
       return stream.read() + stream.read() * 10;
    }

    // ***** when we read the results ******

    int day = readShort(stream); // => 15
    int month = readShort(stream); //  => 2
    int year_suffix = readShort(stream); // => 23
    int hour = readShort(stream); //  => 0
    int minute = readShort(stream); //  => 7
    int second = readShort(stream); // => 59

Now I want to write it back as byte array so I did:

   FileOutputStream stream = new FileOutputStream("/path/to/file");

    writeShort(stream, day);
    writeShort(stream, month);
    writeShort(stream, year);
    writeShort(stream, hour);
    writeShort(stream, minute);
    writeShort(stream, second);


 private static void writeShort(OutputStream stream, int value) throws IOException {
      stream.write(value % 10);
      stream.write(value / 10);
 }

But when I look into output file I see the header is not the same

the value are 05010200 03020000 07000905 instead of 0F000200 17000000 07003B00

please suggest ( picture from Hex fiend editor)

enter image description here


Solution

  • If you really want to read and write short values spread over two bytes, little-endian (i.e., least significant byte first), you can modify your code like this (but there probably is a more efficient way):

    private static int readShort(InputStream stream) throws IOException {
        return stream.read() + stream.read() * 256;
    }
    
    private static void writeShort(OutputStream stream, int value) throws IOException {
        stream.write(value % 256); // or value & 0xFF
        stream.write(value / 256); // or value >> 8
    }
    

    The point is, you don't want to read and write a decimal digit (10 possible values) at a time, but a byte (256 possible values) at a time.