Loading...
Pages: [1]   Go Down
Author Topic: Split Long into bytes, for transmitting over iC2 [SOLVED]  (Read 168 times)
0 Members and 1 Guest are viewing this topic.
Hamme, Belgium
Offline Offline
Sr. Member
****
Karma: 3
Posts: 383
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

I have tried to wrap my head around this one, but I simple can't figure it out.

Thanks to the TimeNTP example I do know how to get 4 bytes into 1 long, like this:

Code:
byte timebuffer[4];
unsigned long highWord = word(timebuffer[0], timebuffer[1]);
unsigned long lowWord = word(timebuffer[2], timebuffer[3]);
unsigned long epoch = highWord << 16 | lowWord;
setTime(epoch);

but now I want to put the unsigned long epoch into 4 bytes, so I can transmit them.

I tried this, but it is incorrect:

Code:
unsigned long epoch;
byte timebuffer[4];
      timebuffer[0] = (byte) epoch;
      timebuffer[1] = (byte) epoch >> 8;
      timebuffer[2] = (byte) epoch >> 16;
      timebuffer[3] = (byte) epoch >> 24;


« Last Edit: February 15, 2012, 03:39:02 am by JO3RI » Logged


Massachusetts, USA
Offline Offline
Tesla Member
***
Karma: 108
Posts: 6611
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I tried this, but it is incorrect:

It would help if you would say in what way the results were "incorrect"

Try without the casting:
Code:
unsigned long epoch;
byte timebuffer[4];
      timebuffer[0] = epoch;
      timebuffer[1] = epoch >> 8;
      timebuffer[2] = epoch >> 16;
      timebuffer[3] = epoch >> 24;

And to make it match the original byte order, take the high byte first:
Code:
unsigned long epoch;
byte timebuffer[4];
      timebuffer[0] = epoch >> 24;
      timebuffer[1] = epoch >> 16;
      timebuffer[2] = epoch >> 8;
      timebuffer[3] = epoch;
Logged

Hamme, Belgium
Offline Offline
Sr. Member
****
Karma: 3
Posts: 383
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

@johnwasser thanks, using your code solved the problem. I did the bit shifting in the wrong order.

Code:
unsigned long epoch;
byte timebuffer[4];
      timebuffer[0] = epoch >> 24;
      timebuffer[1] = epoch >> 16;
      timebuffer[2] = epoch >> 8;
      timebuffer[3] = epoch;
Logged


Pages: [1]   Go Up
Print
 
Jump to: