Question

I have a compressed unsigned char array of a known size. Due to compression considiration I don't store the null-terminator at the end. I want to compare it to another array of the same format. What would be the best way to do so?

I thought duplicating the comparessed arrays to a new array, add the null-terminator, and then compare them using strcmp().

Any better suggestions?

Was it helpful?

Solution

you can use strncmp() function from string.h

strncmp(str1, str2, size_of_your_string); 

Here you can manually give the size of string(or the number of characters that you want to compare). strlen() may not work to get the length of your string because your strings are not terminated with the NUL character.

UPDATE:

see the code for comparison of unsigned char array

#include<stdio.h>
#include<string.h>
main()
{

unsigned char str[]="gangadhar", str1[]="ganga";
if(!strncmp(str,str1,5))
printf("first five charcters of str and str1 are same\n");
else
printf("Not same\n");

}

OTHER TIPS

Since you know the size of the array, you could use strncmp():

int strncmp (char *string1, char *string2, int n)

with n being the number of characters to compare.

Deets: http://www.tutorialspoint.com/ansi_c/c_strncmp.htm

two years later, but...

I believe ‘memcmp‘ is the function you want to use, since ‘strncmp‘ may stop if it found a zero byte inside the compression string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top