简体   繁体   中英

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?

Modify your LENGTH based on the value of buf[4]

int length = buf[4] + 6;

And then the for loop that you already have.

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM