如何检查存储块中的所有字节是否都为零 [英] How to check whether all bytes in a memory block are zero

查看:49
本文介绍了如何检查存储块中的所有字节是否都为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一块内存,其中的元素大小固定,例如100字节,一个又一个地放入其中,所有元素都具有相同的固定长度,所以内存看起来像这样

I have a block of memory with elements of fixed size, say 100 bytes, put into it one after another, all with the same fixed length, so memory looks like this

<element1(100 bytes)><element2(100 bytes)><element3(100 bytes)>...

在某些情况下,我需要确定某个元素的所有字节是否都设置为0字节,因为这具有特殊含义(我并不是说这是一个好主意,但这就是我所处的情况.).

In some situations I need to determine whether all bytes of a certain element are set to the 0-byte because that has a special meaning (I didn't say it was a good idea, but that is the situation I am in).

问题是,我该如何有效地做到这一点.进一步:有一个简单的功能可以做到这一点.为了将字节设置为零,我可以使用memset或bzero,但是我不知道任何用于检查零的函数.

The question is, how do I do that efficiently. Further: is there a simple function to do it. For setting bytes to zero I can used memset or bzero, but I don't know of any function for checking for zero.

此刻我正在使用循环进行支票

At the moment I am using a loop for the check

char *elementStart = memoryBlock + elementNr*fixedElementSize;
bool special = true;
for ( size_t curByteNr=0; curByteNr<fixedElementSize; ++curByteNr )
{
  special &= (*(elementStart+curByteNr)) == 0;
}

当然,我可以使用更大的偏移量循环并使用mword或其他一些合适的更大类型一次检查几个字节.我想这会很有效率,但是我想知道是否有一个功能可以减轻我的负担.

Of course, I could loop with a bigger offset and check several bytes at once with a mword or some other suited bigger type. And I guess that would be rather efficient, but I would like to know whether there is a function to take that burden from me.

建议功能:

  • !memcmp(compareBlock,myBlock,fixedElementSize)

推荐答案

显而易见的可移植,高效的方法是:

The obvious portable, high efficiency method is:

char testblock [fixedElementSize];
memset (testblock, 0, sizeof testblock);

if (!memcmp (testblock, memoryBlock + elementNr*fixedElementSize, fixedElementSize)
   // block is all zero
else  // a byte is non-zero

在大多数实现中,库函数 memcmp()将使用大多数比较中可以使用的最大,最有效的单位大小.

The library function memcmp() in most implementations will use the largest, most efficient unit size it can for the majority of comparisons.

为了提高效率,请不要在运行时设置 testblock :

For more efficiency, don't set testblock at runtime:

static const char testblock [100];

根据定义,除非有初始化程序,否则静态变量会自动初始化为零.

By definition, static variables are automatically initialized to zero unless there is an initializer.

这篇关于如何检查存储块中的所有字节是否都为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆