It is hard to see how your code would ever stop as you are shifting i
to the left by size
while increasing size
. This will grow exponentially until overflow occurs and a crash. If I understand you are simply trying to determine the size of a byte with size_of_byte()
, you are far better served actually checking the number of bits in 1-byte
. By convention, storage for char
is 1-byte
, so if you wanted to prove to yourself that it really contained 8-bits, you would do something like:
/* return the number of bits-per-byte */
size_t szofbyte (void)
{
unsigned char c = 0;
unsigned char sz = 1;
c = ~c; /* invert the bits of c */
while ((c >>= 1)) sz++;
return sz;
}
It may be instructive to visualize the bit operations involved. Simply adding a few printf
statements and outputting the value of the variable you are testing in binary will show what is happening and why and how the loop completes as it should. Here is a short example with an annotated version of the function:
#include <stdio.h>
#ifndef BITS_PER_LONG
#define BITS_PER_LONG 64
#endif
size_t szofbyte_ann (void);
char *binpad (unsigned long n, size_t sz);
int main (void) {
printf ("\n the size of a byte is : %zu bits\n\n", szofbyte_ann());
return 0;
}
/* return the number of bits-per-byte (annotated) */
size_t szofbyte_ann (void)
{
unsigned char c = 0;
unsigned char sz = 1;
c = ~c; /* invert the bits of c */
printf ("\n sz : %hhu c : %s\n", sz, binpad (c, 8));
while ((c >>= 1)) {
sz++;
printf (" sz : %hhu c : %s\n", sz, binpad (c, 8));
}
return sz;
}
/* return binary representation of 'n' paddded to 'sz' chars */
char *binpad (unsigned long n, size_t sz)
{
static char s[BITS_PER_LONG + 1] = {0};
char *p = s + BITS_PER_LONG;
register size_t i;
for (i = 0; i < sz; i++)
*--p = (n>>i & 1) ? '1' : '0';
return p;
}
Output
$ ./szofbyte
sz : 1 c : 11111111
sz : 2 c : 01111111
sz : 3 c : 00111111
sz : 4 c : 00011111
sz : 5 c : 00001111
sz : 6 c : 00000111
sz : 7 c : 00000011
sz : 8 c : 00000001
the size of a byte is : 8 bits