P
P
plat_on2014-05-08 09:13:49
Data types
plat_on, 2014-05-08 09:13:49

Representing numbers in C

Good afternoon!
I think C data types are no secret to anyone.
Char - 1 byte
Int - 4 bytes (for 32 bit machines), etc.
It is also no secret to anyone that the machine stores numbers in binary code.
Dec Bin
0 0
1 1
2 10
3 11
etc.
Accordingly, the unit of type Int will look
like this: 00000000 00000000 00000000 00000001.
To view numbers in the native machine format, you can implement the simplest code:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>

/*
Просмотр чисел в шестнадцатиричной и двоичной системе счисления
*/

int main()
{
  system("chcp 1251 > nul");
  int num;
  printf("Введите число: ");
  scanf("%d", &num);
  printf("\nDEC - %d\tHEX - %#X\tBIN - %d%d%d%d%d%d%d%d %d%d%d%d%d%d%d%d %d%d%d%d%d%d%d%d %d%d%d%d%d%d%d%d\n", num, num, num>>31, (num>>30)%2, (num>>29)%2, (num>>28)%2, (num>>27)%2,(num>>26)%2, (num>>25)%2, (num>>24)%2,
    (num >> 23)%2,(num >> 22)%2,(num >> 21)%2,(num >> 20)%2,(num >> 19)%2,(num >> 18)%2,(num >> 17)%2,(num >> 16)%2,
    (num >> 15)%2,(num >> 14)%2,(num >> 13)%2,(num >> 12)%2,(num >> 11)%2,(num >> 10)%2,(num >> 9)%2,(num >> 8)%2,
    (num >> 7) %2,(num >> 6) %2,(num >> 5) %2,(num >> 4) %2,(num >> 3) %2,(num >> 2) %2,(num >> 1) %2,num % 2);

  

  return 0;
}

Here, for example, is the output for the number 2147483647, which is the maximum for a 4-byte signed int
0d442254c2e94c3daaeca7e5da997090.jpg
. It can be seen that all bits are filled except for the highest one, which is responsible for the sign of the number. Negative numbers are stored in complementary form. They have the most significant bit set to 1.
Here is the output for the number -2147483648
261fe447683147298fc41851a4cf985a.jpg
But if we print the number -1
7c484d4d5eb447ca934b5c78ad6dca27.jpg
Instead of each bit filled with "1", we get "-1".
Actually this is my question - Why is that? Where does the "-" sign come from?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vit, 2014-05-08
@plat_on

You are using the modulo operator (%). The remainder of dividing a negative number by a positive number is either 0 or a negative number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question