Skip to content

Instantly share code, notes, and snippets.

@BobVul
Last active September 21, 2020 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BobVul/5071142 to your computer and use it in GitHub Desktop.
Save BobVul/5071142 to your computer and use it in GitHub Desktop.
Check for nonzero data in a stream, quickly and without output. Answers http://superuser.com/q/559772/117590.
#include <cstdio>
#define BUFFER_SIZE 1024
int main() {
FILE* file = stdin;
char buffer[BUFFER_SIZE];
long long bytes_read = 0;
while (bytes_read = fread(buffer, 1, BUFFER_SIZE, file)) {
for (long long i = 0; i < bytes_read; i++) {
if (buffer[i] != 0) {
printf("Nonzero byte encountered.\n");
return 1;
}
}
}
int error = 0;
if (error = ferror(file)) {
fprintf(stderr, "Error reading file, code: %d\n", error);
return -1;
}
printf("All bytes are zero.\n");
return 0;
}
@rcorsari
Copy link

Hello, one kind curiosity, I'm attempting to learn some basic ANSI C (not C++, though)
I see that you run a "for" cycle to check if the bytes are all 0.
The curiosity and question is this: once you have loaded the buffer, is there a way to make an instant XOR of all its bytes content?
If yes, that would avoid the run of the "for" cycle and so run even faster, isn't it?
Thank you for teaching.
Robert

@BobVul
Copy link
Author

BobVul commented Jun 27, 2019

@rcorsari 5 years late, but ... yea, the faster way would be to use SIMD instructions to process multiple bytes at a time, using SIMD (SSE, AVX, etc.) intrinsics. But they're fairly complex to use. And a good compiler might generate them for a simple loop like this anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment