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
or1
- 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.
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:
While the above functions only support int numbers,
Converting binary string to integer C++
Converting string to int, use stoi(string)
Converting string to ll, use stoll(string)