[SOLVED] - Concatenation

Good Evening,

I was wondering if one of you kind folks can point me in the right direction.

I’m trying to concatenate 4 bytes from an array into an unsigned long. I’ve written a short sketch that hopefully shows what I’m trying to achieve.

If trackInfo[5] == 0x1D, I want to concatenate trackInfo[6], trackInfo[7], trackInfo[8] and trackInfo[9], so that trackLength == 0x45BD5. When this is converted to decimal (285653), it represents the track length in milliseconds.

I’m not sure if it’s important or not, but in this example, trackInfo[6] is 0x00, but it could be non zero values, and by the same token, trackInfo[7] could be 0x00.

My problem is that when I run the sketch, I only get 5BD5, and the 4 has gone AWOL. I’m new to bit shifting, so I’m probably doing something daft, but Google suggests I’m on the right lines.

byte trackInfo [16] = { 
  0xFF, 0x55, 0x0C, 0x04, 0x00, 0x1D, 0x00, 0x04, 0x5B, 0xD5, 0x00, 0x00, 0x21, 0xBD, 0x02, 0xBF };

void setup()

void loop()


void processInfo() {
  if(trackInfo[5] == 0x1D){
    unsigned long trackLength = (trackInfo[6]<<24) | (trackInfo[7]<<16) | (trackInfo[8]<<8) | trackInfo[9];
    Serial.print(trackLength, HEX);

I’ve hopefully explained that well enough to make some sort of sense.



    unsigned long trackLength = (trackInfo[6]<<24) | (trackInfo[7]<<16) | (trackInfo[8]<<8) | trackInfo[9];

What happens to a byte when you shift it 8 or more places to the left?

You are missing some necessary casts.

((unsigned long)trackInfo[6]<<24) | ((unsigned long)trackInfo[7]<<16) | /.....

Thanks Paul,

This appears to work :slight_smile:

unsigned long trackLength = ((unsigned long)trackInfo[6]<<24) | ((unsigned long)trackInfo[7]<<16) | ((unsigned long)trackInfo[8]<<8) | (unsigned long)trackInfo[9];