DEV Community

hacking C++
hacking C++

Posted on

Binary Representations of Numeric Values

The following cheat sheet shows the most common representations of integers, unsigned integers and floating point values used by most hardware platforms and programming languages.
binary represenations of numeric valuesCheck out this tool for visualizing and experimenting with IEEE floating point bit representations.


The Situation in C++

std::numeric_limits<Type>

provides numeric properties for all of C++'s fundamental types (int, float, double, unsigned int, etc.). The cheat sheet below shows how the return value of std::numeric_limits<Type>::member_function() relate to the binary representation of numeric values for Type.
C++ std::numeric_limits cheat sheet

Using numeric_limits

#include <limits>
// smallest negative value:
std::cout << std::numeric_limits<double>::lowest();

// float/double: smallest value > 0
// integers: smallest value
std::cout << std::numeric_limits<double>::min();

// largest positive value:
std::cout << std::numeric_limits<double>::max();

// smallest difference btw. 1 and next value:
std::cout << std::numeric_limits<double>::epsilon();
Enter fullscreen mode Exit fullscreen mode

Bitwise Operations in C++

bitwise operations in C++

Some examples for manipulating the bits of unsigned integers

#include <cstdint>
                             // value | memory bits
std::uint8_t a = 6;          //       | 0000 0110
std::uint8_t b = 0b00001011; //       | 0000 1011
std::uint8_t c1 = (a & b);   // 2     | 0000 0010
std::uint8_t c2 = (a | b);   // 15    | 0000 1111
std::uint8_t c3 = (a ^ b);   // 13    | 0000 1101
std::uint8_t c4 = ~a;        // 249   | 1111 1001
std::uint8_t c5 = ~b;        // 244   | 1111 0100       

// test if int is even/odd:  // result:
bool a_odd  = a & 1;         // 0 => false
bool a_even = !(a & 1);      // 1 => true
Enter fullscreen mode Exit fullscreen mode
#include <cstdint>
                             //     | memory bits
std::uint8_t a = 1;          //     | 0000 0001
a <<= 6;  // 64              //     | 0100 0000
a >>= 4;  // 4               //     | 0000 0100

std::uint8_t b1 = (1 << 1);  // 2   | 0000 0010
std::uint8_t b2 = (1 << 2);  // 4   | 0000 0100
std::uint8_t b3 = (1 << 4);  // 16  | 0001 0000
Enter fullscreen mode Exit fullscreen mode

Type Widths / Memory Sizes of Fundamental Types

memory sizes of fundamental types in C++


For more cool cheat sheets see my collection of C++ cheat sheets.

Top comments (0)