Storing a hex value in a byte array in little endian format

So I am working on a piece of Arduino code in which I have a byte array like this:

 byte bArray[] = {0xC5, 0x41, 0x21, 0x12, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xAA, 0x37, 0x06, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x07, 0x00, 0x00, 0xD0, 0x07, 0x00, 0x00, 0xF4, 0x01, 0x00, 0x00, 0xF4, 0x01, 0x00, 0x00, 0x00, 0x00};

I then have a long value such as:

 long lVal = 523669250;

I need this value to be converted to hex: 0x1F368F02 and then stored in the byte array in positions bArray[14] to bArray[17] in little endian format, such that:

bArray[14] = 0x02, bArray[15] = 0x8F, bArray[16] = 36, bArray[17] = 0x52.

And this is what I am stuck at. Any suggestions as to how to do this would be greatly appreciated!

[/code]

int iVal = 523669250;Unless you're on a Due with 32 bit ints, that won't work.

AWOL: int iVal = 523669250;Unless you're on a Due with 32 bit ints, that won't work.

Right, of course. I was not thinking. The integer value is stored as long then.

Please edit you post and change the quote tags for code tags ;)

int iVal = 523669250;

That int will not contain 523669250 ;) Try a unsigned long.

And if you use a ATmega (aka a processor that is itself little endian) something like

*(unsigned int *)&bArray[14] = iVal;

should do the trick.

Maybe even simply

(unsigned int)bArray[14] = iVal;

but I'm not sure...

Use struct to break the unsigned long into four bytes. The bytes will be in the same order as the long. So you will need four equal statements to get them reversed.

Based on the hints given in Post#1 - Post#4, I have prepared the following solution for you; you may study it.

byte bArray[] = {
0xC5, 0x41, 0x21, 0x12, 0x1C, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE0, 0xAA, 0x37, 0x06, 0x00, 0x00, 0x00, 0x00, 0xD0, 0x07, 0x00, 0x00, 0xD0, 0x07, 0x00, 0x00, 0xF4, 
0x01, 0x00, 0x00, 0xF4, 0x01, 0x00, 0x00, 0x00, 0x00
};
void setup() 
{
  Serial.begin(9600);

  union {
          unsigned long int x = 523669250;
          byte myData[4]; 
        } var;

  for (int i = 0; i<4; i++)
  {
    Serial.println(var.myData[i], HEX);
  }

  for (int i=0, j=14; i<4, j<18; i++, j++)
  {
    bArray[j] = var.myData[i]; 
    Serial.println(bArray[j], HEX);   
  }
  
}


void loop() {
  // put your main code here, to run repeatedly:

}
 for (int i=0, j=14; i<4, j<18; i++, j++)

@GolemMostafa, you will probably want to explain that for loop to the OP, particularly how the comparisons are evaluated, and how the code could be greatly simplified.

uint32_t val = 0x12345678;   // Value to be written 
uint8_t array[24];           // array to which val is to be written
uint8_t ptr = &array[14];    // pointer to first byte to be written
for (int i=0; i<3; i++)
{
    ptr[i] = (uint8_t)(val >> (i * 8));  // get one byte of val, convert to unsigned byte, and write to array
}

Regards,
Ray L.