Bits and Bytes

The basics of bits:

  • At the smallest scale of computers, information is stored as bits and bytes
  • A bit can assume either of two values: 0 or 1
  • A byte consists of 8 bits
    • I keep confusing this and thinking that 1 byte = 4 bits, this is WRONG
  • All computer data is represented using binary, a number system that uses 0s and 1s

Byte = B Bit = b

How are bits stored on a computer?

See Memory (Computer), but basically through registers, RAM, and permanent storage.

Bit-Wise Operator

Arithmetic Overflow and Underflow

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the upper bound of the bit representation.

int x = 2147483647 
cout << x << "\n"; // 2147483647 
x++; 
cout << x << "\n"; // -2147483648 -> Overflow

Overflows are undetected, so be CAREFUL

Most compilers seem to ignore the overflow, resulting in an unexpected or erroneous result being stored. Integer overflows cannot be detected after they have happened, so there is no way for an application to tell if a result it has calculated previously is in fact correct.

C++ Bits

Additional functions The g++ compiler provides the following functions for counting bits: • __builtin_clz(x): the number of zeros at the beginning of the number • __builtin_ctz(x): the number of zeros at the end of the number • __builtin_popcount(x): the number of ones in the number • __builtin_parity(x): the parity (even or odd) of the number of ones The functions can be used as follows:

int x = 5328; // 00000000000000000001010011010000 
cout << __builtin_clz(x) << "\n"; // 19 
cout << __builtin_ctz(x) << "\n"; // 4 
cout << __builtin_popcount(x) << "\n"; // 5 
cout << __builtin_parity(x) << "\n"; // 1 

While the above functions only support int numbers,

Converting binary string to integer C++

string bin_string = "10101010";
int number =0;
 
number = stoi(bin_string, 0, 2);
cout << "bin_string: " << bin_string << endl;
// bin_string: 10101010
cout << "number: " << number << endl;
// number: 170

Converting string to int, use stoi(string) Converting string to ll, use stoll(string)