Home > Software engineering >  Why the strlen() function doesn't return the correct length for a hex string?
Why the strlen() function doesn't return the correct length for a hex string?

Time:12-25

I have a hex string for example \xF5\x17\x30\x91\x00\xA1\xC9\x00\xDF\xFF, when trying to use strlen() function to get the length of that hex string it returns 4!

const char string_[] = { "\xF5\x17\x30\x91\x00\xA1\xC9\x00\xDF\xFF" };
unsigned int string_length = strlen(string_);
printf("%d", string_length); // the result: 4

Is the strlen() function dealing with that hex as a string, or is something unclear to me?

CodePudding user response:

For string functions in the C standard library, a character with value zero, also called a null character, marks the end of a string. Your string contains \x00, which designates a null character, so the string ends there. There are four non-null characters before it, so strlen returns four.

C 2018 7.1.1 1 says:

A string is a contiguous sequence of characters terminated by and including the first null character… The length of a string is the number of bytes preceding the null character…

C 2018 7.24.6.3 2 says:

The strlen function computes the length of the string pointed to by s [its first argument].

You could compute the size of your array as sizeof string_ (because it is an array of char) or sizeof string_ / sizeof *string_ (to compute the number of elements regardless of type), but this will include a terminating null character because defining an array with [] and letting the length be computed from a string literal initializer includes the terminating null character of the string literal. You may need to hard-code the length of the array, possibly using #define to define a preprocessor macro, and use that length in the array definition and in other places where the length is needed.

CodePudding user response:

strlen() iterate to \0 (similar to \x0). Then it count only "\xF5\x17\x30\x91", it's four character.

CodePudding user response:

It is because you have zero at index [4]

string_[0] == 0xF5
string_[1] == 0x17
string_[2] == 0x30
string_[3] == 0x91
string_[4] == 0
...

"\xf5" puts char having integer value 0xf5 at position [0]

To see it as a string you need to escape the \ character

const char string_[] = "\\xF5\\x17\\x30\\x91\\x00\\xA1\\xC9\\x00\\xDF\\xFF";

CodePudding user response:

At compile time, your "string" appears as consecutive hex values expressed in C syntax inside a pair of quotation marks.

strlen() is a run time function that scans through a series of bytes, looking for the first instance of a zero-value byte.

It's good to understand the difference between "compile time" and "run time".

  • Related