简体   繁体   中英

Compare array values to a single value in C

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM