Converting Numbers

Learn why we would need to know how a computer represents numbers in memory.

The need to know number representation

We learned how a computer represents numbers in memory. Do we need this knowledge in practice?

Modern programming languages take care to convert numbers to the correct format. For example, we declare a signed integer variable in decimal notation. We do not need to worry about how the computer stores it in memory… It stores all numbers in two’s complement representation automatically.

There are cases when we want to treat a variable as a set of bits. We declare it as a positive integer in this case. We should operate it in hexadecimal. We don’t need to convert this variable to decimal. This way, we avoid the problems of converting numbers.

The issue arises when we want to read data from some device. Such a task often occurs in system software development. Specialists of this domain deal with device drivers, OS kernels and their modules, system libraries, and network protocol stacks.

Some examples

An example will demonstrate a problem. Let’s suppose we are writing a driver for a peripheral device. It measures air temperature cyclically and sends the results to the CPU. Our task is to interpret this data correctly. Unfortunately, the computer cannot do it for us. This is because the computer and device represent the numbers differently. So, we should write code that does the conversion. We need to know numbers representation to do that.

There is another task that requires us to know the two’s complement. This task is debugging our program. Let’s suppose that the program gives us an unexpectedly large number in the result. If we know the two’s complement, we can guess that an integer overflow happens. This helps us find the root cause of the problem.

Get hands-on with 1200+ tech skills courses.