Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading binary integers

Tags:

People also ask

How do you read a binary number?

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).

Can a human read binary code?

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.

Do you read binary numbers from right to left?

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.

How do you find the binary of an integer?

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.