Search code examples
c++while-loop

how use while and nest while to resolve this data?


I have an hex data arry, like this:

24 00 00 07 01 31 0f 66 65 77 66 63 77 65 72 74
32 35 33 76 73 77 04 31 30 30 30 05 66 65 32 32
66 06 76 77 65 72 67 34

description: '24' is all length of begin '01' to '34'.

'00 00 07' not any sense.

'01' is one byte length of after data, like '31'.

'0f' is 15 byte length of after data, like: 66 65 77 66 63 77 65 72 74 32 35 33 76 73 77.

'04' is 4 byte length of after data, like: 31 30 30 30.

'05' is 5 byte length of after data, like: 66 65 32 32 66.

'06' is 6 byte length of after data, like: 76 77 65 72 67 34.

How can I use while and nest while to resolve it?

I tried to write this code:

    // data arry
    uint8_t data[36] = {0x24, 0x00, 0x00, 0x07, 0x01, 0x31, 0x0f, 0x66, 0x65, 0x77, 0x66, 0x63, 0x77, 0x65, 0x72, 0x74,
                              0x32, 0x35, 0x33, 0x76, 0x73, 0x77, 0x04, 0x31, 0x30, 0x30, 0x30, 0x05, 0x66,
                              0x65, 0x32, 0x32, 0x66, 0x06, 0x76, 0x77, 0x65, 0x72, 0x67, 0x34, 0x24}
    int i = 0, k = 0;
    // rowStart begin for data of 0x01.
    rowStart = 4;
    // 5 is all length of 
    while (i < 5) {
        nextLen = data[rowStart];

        rowStart ++;
        while (k < nextLen) {
            // wish can print 31, 66, 65, 77, 66, 63, 77, 65, 72, 74,
// 32, 35, 33, 76, 73, 77, 31, 30, 30, 30, 66, 65, 32, 32, 66,76, 77, 65, 72, 67, 34.
            printf(" %#x ", data[rowStart + k]); // print data of after length without length
            rowStart ++;  // next length
            k ++;
        }

        i ++;
    }

but this can not solve I question.

I have tried to use while and nest while to solve it, but final I can not solve it.


Solution

  • If you just want to print each string of characters then you can use the following:

    int total = data[0];
    uint8_t* pData = data + 4;
    while (total > 0)
    {
        int length = *pData++;
        printf("%.*s\n", length, pData);
        pData += length;
        total -= length + 1;
    }
    

    If you want to print the hex values then you will need something like the following instead of the above printf statement:

    for (int i = 0; i < length; ++i)
    {
        printf("0x%.2X, ", pData[i]);
    }
    printf("\n");