Search code examples
cbit32-bit

Converting 32 bit number to four 8bit numbers


I am trying to convert the input from a device (always integer between 1 and 600000) to four 8-bit integers.

For example,

If the input is 32700, I want 188 127 00 00.

I achieved this by using:

32700 % 256 
32700 / 256 

The above works till 32700. From 32800 onward, I start getting incorrect conversions.

I am totally new to this and would like some help to understand how this can be done properly.


Solution

  • I ended up doing this:

    unsigned char bytes[4];
    unsigned long n;
    
    n = (unsigned long) sensore1 * 100;
    
    bytes[0] = n & 0xFF;     
    bytes[1] = (n >> 8) & 0xFF;
    bytes[2] = (n >> 16) & 0xFF;
    bytes[3] = (n >> 24) & 0xFF;
           CAN_WRITE(0x7FD,8,01,sizeof(n),bytes[0],bytes[1],bytes[2],bytes[3],07,255);