I\'m looking for the most efficient way to calculate the minimum number of bytes needed to store an integer without losing precision.
e.g.
int: 10 = 1 byte
I think this is a portable implementation of the straightforward formula:
#include
#include
#include
int main(void) {
int i;
unsigned int values[] = {10, 257, 67898, 140000, INT_MAX, INT_MIN};
for ( i = 0; i < sizeof(values)/sizeof(values[0]); ++i) {
printf("%d needs %.0f bytes\n",
values[i],
1.0 + floor(log(values[i]) / (M_LN2 * CHAR_BIT))
);
}
return 0;
}
Output:
10 needs 1 bytes 257 needs 2 bytes 67898 needs 3 bytes 140000 needs 3 bytes 2147483647 needs 4 bytes -2147483648 needs 4 bytes
Whether and how much the lack of speed and the need to link floating point libraries depends on your needs.