Problem with Hex and Char

Hello...

I have a little problem with my program, i need to send over TCP a value...

This is my function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
char *HexToAscii(char *hexa)
{
    int i = 0;
    int j = 0;
    char *numDec;
    char numHex[5];
    char *numASCII;

    numHex[0] = '0';
    numHex[1] = 'x';
    numHex[4] = '\0';

    numASCII = (char *) malloc ((strlen(hexa) / 2) * sizeof(char));
    numASCII[0] = '\0';

    for(i = 0; i <= strlen(hexa); i+=2) {
        numHex[2] = cad[i];
        numHex[3] = cad[i + 1];
        numASCII[j] = strtol(numHex, &numDec, 16);
        j++;
    }
    return numASCII;
}


When i send some like: "02 01 CF 06 09 29 02 58 B0", all works perfect, but if i try to send "02 01 CF 00 09 04", fails... the problem is the 00. The strtol function give a 0, and that in the char[] is like "\0"... so the function, cut the string at the "00".
And the hardware in the other side, expect de "00" as part of the data.

Can someone help me with this prob ?

Thanks you !
char* -- ie, C-style strings-- are by definition ASCIIZ (\0) terminated. Therefore, you cannot achieve what
you want to without also returning a hand-computed length (and thus strlen() will not work).

Alternatively, you could use a C++ string -- std::string -- which will handle embedded \0 just fine.
Topic archived. No new replies allowed.