# Bit-Sizes of Stuff

CS 301 Lecture, Dr. Lawlor

## Bit Fields

So, a 1-bit field can store two values (0 and 1).  A 2-bit field four values (00, 01, 10, and 11).  A 3-bit field eight values (000, 001, ..., 111).  An n-bit field can store 2n values.   Here are the typical useful values:

 Bits Values Example 1 2 Current in a wire. 2 4 x86 "ModR/M" byte type field. HW2.3 high bits 3 8 One octal digit.  x86 register. HW2.3 "funkcode" 4 16 One hexadecimal ("hex") digit.  Motorola 68000 register. 5 32 PowerPC, MIPS, SPARC register number. 8 256 One byte.  "signed char" (-128 to +127) or "unsigned char" (0 to +255). 16 65,536 "short" (-32K to +32K) or "unsigned short" (0 to +64K) 32 4.29 billion "int" (-2.14G to +2.14G) or "unsigned int" (0 to +4.29G) 64 18.4 billion-billion long long, or on some machines, just "long"

## Sizes of Actual Language Elements

There's a nice little builtin function in C/C++ called "sizeof" that returns the number of bytes (technically, the number of characters) used by a variable or data type.  Sadly, C/C++ don't specify how many bytes various data types like "int" have, so it depends on the machine:
 32-bit x86 (little endian) 32-bit PowerPC (big endian) 64-bit x86 or Itanium Java / C# `sizeof(char)==1sizeof(short)==2sizeof(int)==4sizeof(long)==4sizeof(long long)==8sizeof(void *)==4sizeof(float)==4sizeof(double)==8sizeof(long double)==12` `sizeof(char)==1sizeof(short)==2sizeof(int)==4sizeof(long)==4sizeof(long long)==8sizeof(void *)==4sizeof(float)==4sizeof(double)==8sizeof(long double)==8` `sizeof(char)==1sizeof(short)==2sizeof(int)==4sizeof(long)==8sizeof(long long)==8sizeof(void *)==8sizeof(float)==4sizeof(double)==8sizeof(long double)==16` `sizeof(byte)==1sizeof(short)==2sizeof(int)==4sizeof(long)==8 /* no need for long long */ /* no pointers in Java */sizeof(float)==4sizeof(double)==8 /* no long double in Java */sizeof(Char)==2`
Note the deciding difference between "32 bit machines" and "64 bit machines" is the size of a pointer--4 or 8 bytes.  "int" is 4 bytes on all modern machines.  "long" is 8 bytes in Java or a 64-bit machine, and just 4 bytes on 32-bit machines.

Here's a program that prints out the above:
`char c;short s;int i;long l;long long ll;void *v;float f;double d;long double ld;std::cout<<"sizeof(char)=="<<sizeof(c)<<"\n";std::cout<<"sizeof(short)=="<<sizeof(s)<<"\n";std::cout<<"sizeof(int)=="<<sizeof(i)<<"\n";std::cout<<"sizeof(long)=="<<sizeof(l)<<"\n";std::cout<<"sizeof(long long)=="<<sizeof(ll)<<"\n";std::cout<<"sizeof(void *)=="<<sizeof(v)<<"\n";std::cout<<"sizeof(float)=="<<sizeof(f)<<"\n";std::cout<<"sizeof(double)=="<<sizeof(d)<<"\n";std::cout<<"sizeof(long double)=="<<sizeof(ld)<<"\n";return 0;`