Muhammed Yıldız Muhammed Yıldız - 2 months ago 7
C++ Question

Writing data depending on length of array in C++

I take data from serial port using below code:

for (sa = 0; sa < 15; sa++) {
printf("::%0.2X", buf[sa]);
}


I take data that have different length like below.
buf[4]
defines length of array. For example, if
buf[4] == 07
there are 13 elements in array; if
buf[4] == 09
there are 15 elements in array.

Data 1:
::02::03::98::00::07::20::16::09::30::13::15::23::B6::


Data 2:
::02::03::99::00::09::20::16::09::30::13::15::25::23::00::9C


I want to write code like above and my integer
LENGTH
will vary depending on the length of
buf[]
array.

for (sa = 0; sa < LENGTH; sa++) {
printf("::%0.2X", buf[sa]);
}


Do you have any idea?

Answer

I would say:

for(sa=0;sa<buf[4]+5;sa++){
    printf("::%0.2X",buf[sa]);
}

If however you only get one element at a time, you can do instead:

for(sa=0;sa<4;sa++){
    printf("::%0.2X",buf[sa]);
}
int length = buf[4] + 1;
printf("::%0.2X",length); //prints buf[4]
for(sa=0;sa<length;sa++){
    printf("::%0.2X",buf[sa+5]);
}
Comments