Reputation: 1393
I have a buffer of size 1500. In that buffer I need to check whether 15 bytes are all zeros or not (from 100 to 115). How can we do this (if we do not use any loop for it)? Data is of type "unsigned char", actually it is an unsigned char array.
Platform : Linux, C, gcc compiler
Will using memcmp()
be correct or not? I am reading some data from a smart card and storing them in a buffer. Now I need to check whether the last 15 bytes are consecutively zeros or not.
I mentioned memcmp()
here because I need an efficient approach; already the smart card reading has taken some time.
Or going for bitwise comparison will be correct or not . Please suggest .
Upvotes: 4
Views: 8382
Reputation: 1393
I implemented like this :
699 int is_empty_buffer(unsigned char *buff , size_t size)
700 {
701 return *buff || memcmp(buff , buff+1, size);
702 }
703
if the return value is zero then it's empty
Upvotes: 0
Reputation: 2993
100 to 115 is not 15 byte, it is 16 byte. I assume int size is 16 byte in your system.
if (0 == *((unsigned int*)(buffer + 100))) {
// all are zero
}
Upvotes: 1
Reputation: 182829
Use a loop. It's the clearest, most accurate way to express your intent. The compiler will optimize it as much as possible. By "optimizing" it yourself, you can actually make things worse.
True story, happened to me a few days ago: I was 'optimizing' a comparison function between two 256-bit integers. The old version used a for
loop to compare the 8 32-bit integers that comprised the 256-bit integers, I changed it to a memcmp
. It was slower. Turns out that my 'optimization' blinded the compiler to the fact that both buffers were 32-bit aligned, causing it to use a less efficient comparison routine. It had already optimized out my loop anyway.
Upvotes: 2
Reputation: 597166
unsigned char buffer[1500];
...
bool allZeros = true;
for (int i = 99; i < 115; ++i)
{
if (buffer[i] != 0)
{
allZeros = false;
break;
}
}
.
static const unsigned char zeros[15] = {0};
...
unsigned char buffer[1500];
...
bool allZeros = (memcmp(&buffer[99], zeros, 15) == 0);
Upvotes: 5