Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of bits in a data type

Tags:

c

sizeof

I have two tasks for an assignment, one return the number of bits in type int on any machine. I thought I would write my function like so:

int CountIntBitsF() {
    int x = sizeof(int) / 8;
    return x;
}

Does that look right?

The second part is to return the number of any bits of any data type with a macro, and the macro can be taken from limits.h. I looked up limits.h on my machine, and also http://www.opengroup.org/onlinepubs/007908799/xsh/limits.h.html, but I don't think I really understand how any of those would return the number of bits in any data type. Any thoughts? Thanks.

like image 981
Crystal Avatar asked Jan 19 '10 02:01

Crystal


People also ask

How many bits are in each data type?

Fundamental Data TypesA byte is eight bits, a word is 2 bytes (16 bits), a doubleword is 4 bytes (32 bits), and a quadword is 8 bytes (64 bits). Figure 29-2 shows the byte order of each of the fundamental data types when referenced as operands in memory.

What data type has 8 bits?

The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256 values. The char type can contain both positive and negative values. The range of values is from -128 to 127.

What data type has 32 bits?

int , long , ptr , and off_t are all 32 bits (4 bytes) in size. int is 32 bits in size. long , ptr , and off_t are all 64 bits (8 bytes) in size.


2 Answers

The fundamental unit of storage is a char. It is not always 8 bits wide. CHAR_BIT is defined in limits.h and has the number of bits in a char.

like image 195
Justin Smith Avatar answered Sep 29 '22 01:09

Justin Smith


It's *, not /.

As for the second part, see the "Numerical Limits" section.

like image 26
Ignacio Vazquez-Abrams Avatar answered Sep 29 '22 01:09

Ignacio Vazquez-Abrams