Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a buffer in C?

Tags:

c

string

linux

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 .

like image 674
john Avatar asked Oct 27 '25 23:10

john


2 Answers

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);
like image 74
Remy Lebeau Avatar answered Oct 30 '25 12:10

Remy Lebeau


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.

like image 43
David Schwartz Avatar answered Oct 30 '25 11:10

David Schwartz