To understand a number in binary, for whole numbers we need to recognise that the most significant binary digit (or bit for short) is on the left and least significant bit is on the right. As we look right to left, each bit represents a higher power of 2 (because binary is base 2).
However, just as human-readable information can be converted into binary, binary can be converted into common English without the use of computers! We can read the binary language, but to do that we need to understand the numeric system.
Multiply each binary digit by two to the power of its place number. Remember, binary is read from right to left. The rightmost place number being zero.
To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order. Here is an example of such conversion using the integer 12.
const unsigned char* p;
int64_t u = ...; // ??
What's the recommended way to read a 64-bit binary little endian integer from the 8 bytes pointed to by p? On x64 a single machine instruction should do, but on big-endian hardware swaps are needed. How does one do this both optimally and portably?
Carl's solution is good, portable enough but not optimal. This begs the question: why doesn't C/C++ provide a better and standardized way to do this? It's not an uncommon construct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With