简体   繁体   English

将数组值与C中的单个值进行比较

[英]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. 我需要比较数组中的某些值以查看它们是否都是相同的单个值,比如说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: 是否有一个通用的函数来执行此操作,例如memcmp(),还是我必须用一种困难的方法来检查每个显式值,例如:

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. 显然,我可以像memcmp一样使用自己的函数来执行此操作,但是如果不需要的话,我不想重新发明轮子。

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. 从您的答案中我看到您需要比较字节,在这种情况下string.h支持memchrstrchr及其派生类,具体取决于您要使用它的程度。

If you wanted to implement it yourself, and performance is an issue, i'd suggest inlining a block of assembly doing rep scasb 如果您想自己实现它,而性能是一个问题,我建议内联一个rep scasb的程序集

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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