0

I need to compare some of the values in an array to see if they are all the same single value, let's say 0xFF. Is there a common function to do this, like memcmp(), or do I have to do it the hard way and check every explicit value, like:

if ( ary[3] == 0xFF && ary[4] == 0xFF && ary[5] == 0xFF && ary[6] == 0xFF ... )
{
// do something
}

I can obviously make my own function to do it like memcmp, but I don't want to reinvent the wheel if I don't have to.

2 Answers 2

1

I suppose a completely generic function would look something like this:

#include <string.h>

bool check_array (const void*  array, 
                  size_t       array_n
                  const void*  value, 
                  size_t       type_size)
{
  const uint8_t* begin    = array;
  const uint8_t* end      = begin + array_n * type_size;
  const uint8_t* byte_val = value;
  const uint8_t* byte_ptr;

  for(byte_ptr = begin; byte_ptr < end; byte_ptr += type_size)
  {
    if( memcmp(byte_ptr,
               byte_val,
               type_size) != 0 )
    {
      return false;
    }
  }  

  return true;
}


int main()
{
  int array [] = { ... };

  bool result = check_array (array, 
                             sizeof(array), 
                             0x12345678,
                             sizeof(int));
}
Sign up to request clarification or add additional context in comments.

Comments

0

From your answer I see you need to compare bytes, in that case string.h supports memchr, strchr and their derivatives, depending on how exactly you want to use it.

If you wanted to implement it yourself, and performance is an issue, i'd suggest inlining a block of assembly doing rep scasb

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.