Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are all datatypes a power of 2?

Why are all data type sizes always a power of 2?

Let's take two examples:

short int 16
char 8

Why are they not the like following?

short int 12
like image 919
Vivek Goel Avatar asked Mar 04 '11 09:03

Vivek Goel


People also ask

Why are bits in powers of 2?

Because two is the base of the binary numeral system, powers of two are common in computer science. Written in binary, a power of two always has the form 100...000 or 0.00... 001, just like a power of 10 in the decimal system.

What are the 2 data types?

Note: Data types should not be confused with the two types of data that are collectively referred to as customer data: entity data and event data. To properly define event properties and entity properties, you need a good understanding of data types.

What is data type have two value?

boolean: The boolean data type has only two possible values: true and false .


2 Answers

That's an implementation detail, and it isn't always the case. Some exotic architectures have non-power-of-two data types. For example, 36-bit words were common at one stage.

The reason powers of two are almost universal these days is that it typically simplifies internal hardware implementations. As a hypothetical example (I don't do hardware, so I have to confess that this is mostly guesswork), the portion of an opcode that indicates how large one of its arguments is might be stored as the power-of-two index of the number of bytes in the argument, thus two bits is sufficient to express which of 8, 16, 32 or 64 bits the argument is, and the circuitry required to convert that into the appropriate latching signals would be quite simple.

like image 167
Marcelo Cantos Avatar answered Oct 22 '22 12:10

Marcelo Cantos


The reason why builtin types are those sizes is simply that this is what CPUs support natively, i.e. it is the fastest and easiest. No other reason.

As for structs, you can have variables in there which have (almost) any number of bits, but you will usually want to stay with integral types unless there is a really urgent reason for doing otherwise.

You will also usually want to group identical-size types together and start a struct with the largest types (usually pointers).
That will avoid needless padding and it will make sure you don't have access penalties that some CPUs exhibit with misaligned fields (some CPUs may even trigger an exception on unaligned access, but in this case the compiler would add padding to avoid it, anyway).

like image 34
Damon Avatar answered Oct 22 '22 14:10

Damon