0

I am a beginner and I want to divide a long gettime into 4 shorts for the Modbus protocol, but it does not always work. I don't know why (maybe because of the casting). I hope someone may help me :)

Thanks in advance to those who can enlighten me!

public void SetUp() {
    long time = new Date().getTime();  // time in ms since epoch
    System.out.println(time);
    int high32 = (int)(time >> 32);
    int low32 = (int)time;
    long l = (((long)high32) << 32) | (low32 & 0xffffffffL);
    short low16_1 = (short) high32;
    short high16_1= (short) (high32 >> 16);
    int complete = low16_1 | (high16_1 << 16);
    short low16_2 = (short) low32;
    short high16_2= (short) (low32 >> 16);
    int complete2 = low16_2 | (high16_2 << 16);
    long d = (((long)complete) << 32) | (complete2 & 0xffffffffL);
    System.out.println(l);      
    System.out.println(d);
    Date e = new Date (time);
    System.out.println(e);
    Date g = new Date (d);
    System.out.println(g);
}

Display example :

1530430114623
1530430114623
1530430114623
Sun Jul 01 09:28:34 CEST 2018
Sun Jul 01 09:28:34 CEST 2018

1530431375214
1530431375214
1533303293806
Sun Jul 01 09:49:35 CEST 2018
Fri Aug 03 15:34:53 CEST 2018
dda
  • 6,030
  • 2
  • 25
  • 34
Gabriel
  • 319
  • 3
  • 15
  • Notice the difference between the way you convert from two shorts to an int and the way you convert from two ints to a long? That mask is important! – RealSkeptic Jul 01 '18 at 08:04
  • Oh, I thought it did not affect... Thank you very much for your answer ! – Gabriel Jul 01 '18 at 08:20
  • Using union is a faster and cleaner method for this any day. It requires less processing, and the method is standard for any data type. You just have to know how much ram the datatype takes. – Nitro Jul 01 '18 at 08:29

1 Answers1

0

Just use a union

This is how to convert from 1 long(32 bits) to 4 uint8 (8bit)

union convertor{
long input;
uint8_t output[4];
}

convertor entry;
entry.input=new Date().getTime()
//the value will be split into 4 unit8_t of entry.output

You can do something similar with unit16_t, here you will have to use 2 unit16_t instead of 4.

You can then combine the shorts together in the same ourder where it is being received to get the original time value

for(int i=0;i<4;i++)
entry.output[i]=data[i];
//get the original value from entry.intput as long
Nitro
  • 1,063
  • 1
  • 7
  • 17
  • Note the tag [tag:java] on the OP. – RealSkeptic Jul 01 '18 at 14:33
  • I reached here because of the tag Arduino, which is C programming. Also the setup function is used in Arduino. @Gabriel, what are you coding for, and which language are you using? – Nitro Jul 01 '18 at 18:09
  • Modbus Master in java Modbus Slave on the arduino: this is the code for the master here. It's good I found the answer (error in the mask thanks RealSkeptic) Thank you very much for your help ! – Gabriel Jul 05 '18 at 13:06