0

I have a const char* pointing to data in hex format, I need to find the length of the data for that I am checking for NUL-terminator but when \x00 comes up it detects it as NUL-terminator returning incorrect length.
How can I get around that?

const char* orig = "\x09\x00\x04\x00\x02\x00\x10\x00\x42\x00\x02\x00\x01\x80\x0f\x00"
uint64_t get_char_ptr_len(const char *c)
{
    uint64_t len = 0;
    if (*c)
    {
        while (c[len] != '\0') {
            len++;
        }
    }
    return len;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Aamir Shaikh
  • 345
  • 1
  • 2
  • 13

2 Answers2

2

\x00 is the NUL terminator; in facts, \x00 is just another way to write \0.

If you have byte data that contains embedded NULs, you cannot use NUL as a terminator, period; you have to keep both a pointer to the data and the data size, exactly as function that operate on "raw bytes" (such as memcpy or fwrite) do.

As for literals, make sure you initialize an array (and not just take a pointer to it) to be able to retrieve its size using sizeof:

const char orig[] = "\x09\x00\x04\x00\x02\x00\x10\x00\x42\x00\x02\x00\x01\x80\x0f\x00";

Now you can use sizeof(orig) to get its size (which will be one longer than the number of explicitly-written characters, as there's the implicit NUL terminator at the end); careful though, as arrays decay to pointer at pretty much every available occasion, in particular when being passed to functions.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
0

\x indicates hexadecimal notation.

Have a look at an ASCII table to see what \x00 represent.

\x00 = NULL // In Hexadecimal notation.

\x00 is just another way to write \0.

Try

const char orig[] = "\x09\x00\x04\x00\x02\x00\x10\x00\x42\x00\x02\x00\x01\x80\x0f\x00";

and

len=sizeof(orig)/sizeof(char);
anoopknr
  • 3,177
  • 2
  • 23
  • 33