Skip to content

Instantly share code, notes, and snippets.

@lmumar
Created April 9, 2014 14:26
Show Gist options
  • Save lmumar/10276617 to your computer and use it in GitHub Desktop.
Save lmumar/10276617 to your computer and use it in GitHub Desktop.
c function that will count the number of bytes needed to store a value
/*
* compile with:
* g++ -lm bcount.c -o bcount
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char **argv) {
long num = atol(argv[1]);
long cnt = 0;
long min = (num < 0) ? -1 : 0;
while (num != min) {
num >>= 1;
cnt++;
}
printf("total bytes %lu\n", (long)ceil(cnt/8.0));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment