Reputation: 3706
Here's a couple of thoughts.I'm learning so there might be mistake(s) and even missing some basics.
sizeof
operator returns number of bytes.number of bits in byte
is not constant value(correct me but it's number of bits char has).So I came up with this piece of (probably unnecessary) code:
#include <stdio.h>
#include <math.h>
#include <limits.h>
int main(void)
{
double bits;
bits=sizeof(int)*log10(UCHAR_MAX+1)/log10(2);
printf("Bits = %lf\n", bits);
return 0;
}
Is there easier (standard) way to check how many bits
given type occupies?
CHAR_BIT * sizeof(type)
will do the job, but is there standard one argument
macro/function that does that for me?
Someone with better mathematical background could check if my code will be always giving correct answers.
Upvotes: 1
Views: 1545
Reputation: 658
char data type is a byte. a int is 4bytes (dword). short is 2bytes (word). so, how many bits? just sizeof(the_char)*8. when you want to convert bytes to bits just bits_number=bytes_number*8 :)
Upvotes: 0
Reputation: 6886
If you want to check for how many bits the machine actually used for a single char use the CHAR_BIT
macro (note that sizeof (char)
will always return one by definition though the actual allocation size per char may be still taller (even 32bits) though wasteful)
I am not aware of any predefined macro, but
#define REAL_BITS(type) (CHAR_BIT*sizeof(type))
should suffice
Upvotes: 2
Reputation: 5381
Using CHAR_BIT (defined in limits.h) should do it.
CHAR_BIT * sizeof(something)
I have checked a number of *nix platforms and they are all 8 bits in a byte, but I guess it may vary on some stranger platforms.
Upvotes: 1