简体   繁体   中英

Convert an integer to BYTE value

I'm trying to write some command to serial comm port. Say I need to send 10 bytes of data to comm port. Now out of that 10 bytes, data message is something like:

Byte offset 0    - message id
Byte offset 1-4  - unix time in format 1432419028
Byte offset 5-10 - data

My query is how do I convert unix time 1432419028 to fit in my BYTE array. Platform is C++ Visual Studio.

I got some sample to write like

  BYTE initmsg[10];
  unsigned int* UNALIGNED epoch_time = (unsigned int*) &initmsg[1];
  *epoch_time = 12345678;

But I would like to construct the initmsg look like below.

  initmsg[1] = 0x01;
  initmsg[2] = 0x01;
  initmsg[3] = 0x01;
  initmsg[4] = 0x01;

The proper portable way would be, in Big-Endian:

uint32_t time = ...;
initmsg[1] = (time >> 24) & 0xFF;
initmsg[2] = (time >> 16) & 0xFF;
initmsg[3] = (time >> 8) & 0xFF;
initmsg[4] = time & 0xFF;

And in Little-Endian:

uint32_t time = ...;
initmsg[1] = time & 0xFF;
initmsg[2] = (time >> 8) & 0xFF;
initmsg[3] = (time >> 16) & 0xFF;
initmsg[4] = (time >> 24) & 0xFF;

What endianness to use is not related to the architecture in use, but should be specified in the documentation. If it is not, well, trial and error...

UPDATE : Why is that? You have to look at the bits, for example one of the middle bytes:

       31            24              16               8               0
time:
        X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X

time >> 16:
        > > > > > > > > > > > > > > > > X X X X X X X X X X X X X X X X

(time >> 16) & 0xFF:
 0xFF = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
      & > > > > > > > > > > > > > > > > X X X X X X X X X X X X X X X X
      = 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 X X X X X X X X

That is, you shift the bits to put the ones you want in bit positions 0-7, and then do a binary AND with 0xFF to zero out any other bit except 0-7. Naturally, you are truncating to a byte when assigning to the array, so this last step is not strictly necessary, but I find a good practice to explicitly do the & 0xFF .

It is also useful to think in hexadecimal:

1432419028 = 0x5560FAD4

0x5560FAD4 >> 24 = 0x55
0x5560FAD4 >> 16 = 0x5560
0x5560FAD4 >>  8 = 0x5560FA
0x5560FAD4 >>  0 = 0x5560FAD4

(0x5560FAD4 >> 24) & 0xFF = 0x55
(0x5560FAD4 >> 16) & 0xFF = 0x60
(0x5560FAD4 >>  8) & 0xFF = 0xFA
(0x5560FAD4 >>  0) & 0xFF = 0xD4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM