Converting a unsigned long into 4 byte array

Hi,

i'm triying to chop an unsigned long (32 bit) value into four bytes array, in order to send them via the I2C command Wire.write(my_array, 4); but I don't know how I should do this.

Please, can you help me? Sorry for my bad english

Use bit shifting and masking:

This will do little-endian - i.e., least significant byte first:

unsigned long valye = 0x12345678;

byte arr[4];

arr[0] = value & 0xFF; // 0x78
arr[1] = (value >> 8) & 0xFF // 0x56
arr[2] = (value >> 16) & 0xFF // 0x34
arr[3] = (value >> 24) & 0xFF // 0x12

i'm triying to chop an unsigned long (32 bit) value into four bytes array, in order to send them via the I2C command

Why do you think you need to?

If you are convinced that you do, a union is one way:

union
{
   long a;
   byte b[4];
} stuff;

stuff sendThis;
sendThis.a = yourLong;

Then, you can send sendThis.b.

But, you can simply cast yourLong to a byte pointer, using (byte *)yourLong, and the compiler knows how to send the 4 bytes.

PaulS: But, you can simply cast yourLong to a byte pointer, using (byte *)yourLong, and the compiler knows how to send the 4 bytes.

Remember to take the address of the object first:

(byte *) &yourLong

pYro_65: Remember to take the address of the object first:

(byte *) &yourLong

That's the way to do it, but remember that different computer architectures have different ways to represent integer values in memory, so don't assume that if you put the same four bytes together in the same order in a different device that they will represent the same unsigned long value. If the sender and receiver share the same architecture then it will simply work, but if they are different architectures then they might do, or they might not. The preferred general way to deal with this would be to define a network byte order (TCP/IP 'big-endian' byte ordering would be the obvious choice) and have each device deal with any re-ordering needed to convert that network byte order to the local architecture's order. The 'C' runtime library provides standard functions hton() and htons() etc to deal with that for you if you adopt the TCP/IP network byte order standard.