Odd need to convert unsigned long to a byte array

Hi gang,

I am stumped.
I need to convert an input of (something like): "12345678" to an array of bytes to be output to Serial.write that looks like:

int inputLong = 12345678;

to:

byte outputArray[4] = {0x12,0x34,0x56,0x78};

I've looked at things like atoi, etc .. but am still completely stumped as to how to accomplish this task.
Any help is much appreciated!

int inputLong = 12345678;

Interesting way to declare a long.

  long inputLong = 12345678;
  Serial.write( (const uint8_t*)(&inputLong), sizeof(inputLong) );

Unions are perfect for this.

struct splitLong {
  union {
    long value;
    char split[4];
  }__attribute__((packed));
};

struct splitLong myLong;

myLong.value = 12345678;

Then you can access the individual bytes of the long using:

myLong.split[0], myLong.split[1], myLong.split[2] and myLong.split[3].

However, that won't give you bytes in the form you are after, but the raw bytes of the long variable. The data isn't stored in the way you think.

The value 12345678 is actually stored as 0x00, 0xbc 0x61, 0x4e (or is it the other way around on the avr-gcc? Is it big or little endian?)

To get the bytes you are surmising you want you would need to convert to Binary Coded Decimal which is like working in hexadecimal and ignoring any numbers above 9.

The hexadecimal bytes 0x12, 0x34, 0x45, 0x67 would actually equate to 305419896.

Is it big or little endian?)

Big endian.

AWOL:

Is it big or little endian?)

Big endian.

Good-o. I like a good big end :stuck_out_tongue:

Why do you need to convert an integer to a byte array for Serial.write? If you want to send an integer from the Arduino to a PC in binary form, you can use the method Coding Badly suggested. However, you will probably have to take into account the endianess in both system. Normally if you send integers between different machines/OSs, you convert them into and from the network byte order using hton{l,s} and ntoh{l,s} functions, i,e.:

// In the sending end
outputLong = htonl(outputLong);

// In the receiving end
inputLong = ntohl(inputLong)