7

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?

alk
  • 69,737
  • 10
  • 105
  • 255
David Tzoor
  • 987
  • 4
  • 16
  • 33

3 Answers3

9

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");

}
Gangadhar
  • 10,248
  • 3
  • 31
  • 50
  • 1
    Does strncmp work on unsigned char strings as well? @Gangadher – David Tzoor Aug 26 '13 at 05:57
  • 1
    @DavidTzoor yes, it does. – verbose Aug 26 '13 at 05:58
  • @DavidTzoor yes, it works see the simple example added to the answer. – Gangadhar Aug 26 '13 at 06:07
  • 2
    Actually, it will only work for your case -- *compressed* binary data -- because this typically will not contain zero bytes. Any zero byte will terminate the strncmp operation prematurely -- [strncmp definition](http://www.cplusplus.com/reference/cstring/strncmp/). – Jongware Aug 26 '13 at 20:10
  • For c++, [cppreference.com](https://en.cppreference.com/w/cpp/string/byte/strncmp) says: "The behavior [of strncmp(lhs, rhs, count)] is undefined if lhs or rhs are not pointers to null-terminated strings.", however, it looks like it's safe for C. – Vaelus Jul 18 '19 at 18:32
3

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.

Nick
  • 9,962
  • 4
  • 42
  • 80
2

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

verbose
  • 7,827
  • 1
  • 25
  • 40