1

I know in C# we can add 2 different integer types, say a variable of type int to a variable of type long

eg

int i = 1;
long l = 2;
long l2 =  i + l; //fine

How is this possible?

Because since the int is of 32 bits if I were to have a negative integer the MSB will become 1 so:-

-1 will be represented as 10000000000000000000000000000001 (in signed magnitude way)

Now, my question is how does compiler gets to know that the above 32 bit number is -1 or 2147483649?

And if it were to convert the 32 bit number to 64 bit isn't it going to loose the MSB resulting in getting wrong value?

If we do casting -1 in 32 bit becomes like this in 64 bit.

0000000000000000000000000000000010000000000000000000000000000001

loosing the MSB?

Hope you get my confusion.

Shad
  • 1,185
  • 1
  • 12
  • 27
  • 1
    `Now, my question is how does compiler gets to know that the above 32 bit number is -1 or 2147483649?` What do you mean by that? The compiler knows because programmers programmed the rules of how to treat numbers in the compiler. `And if it were to convert the 32 bit number to 64 bit isn't it going to loose the MSB resulting in getting wrong value?` No. – tkausl Aug 07 '22 at 02:38
  • 2
    `-1 will be represented as 10000000000000000000000000000001` x86 uses two's complement. Your `-1` is stored as `11111111111111111111111111111111`. – tkausl Aug 07 '22 at 02:39
  • @tkausl updated my question for "What do I mean by that". – Shad Aug 07 '22 at 02:42
  • two's complement. Oh okay, that makes more sense. – Shad Aug 07 '22 at 02:44
  • 1
    You don't loose the sign. The number will be sign-extended, meaning the sign bit will be copied to the "new" 32 bits, resulting in the exact same number. – tkausl Aug 07 '22 at 02:44
  • 1
    `Now, my question is how does compiler gets to know that the above 32 bit number is -1 or 2147483649?` I think I understood this part now; It knows because the programmer declared it as either being signed or unsigned. – tkausl Aug 07 '22 at 02:46
  • @tkausl okay but if that number was representing 2147483649 the signed bit isn't going to be copied? By default, int is signed. – Shad Aug 07 '22 at 02:47
  • 1
    `2147483649` cannot be stored in a signed 32 bit integer. unsigned integers zero-extend instead of sign-extend. – tkausl Aug 07 '22 at 02:50
  • 1
    This is everyday research for me but what you have is called binary addition and end-carry-round… see this for more… https://en.wikipedia.org/wiki/Signed_number_representations but the biggest thing to look at is the indices. 127 can be both -127 to +127. The sign + or - is ignored. The binary number value depends on the nth possible outcome with a carry round addition. You have to remember int 1 is not 1 it’s int 10000001 so therefore mathematically it’s done in binary not what we actually see as math. – Camp Nerd Aug 07 '22 at 03:14

0 Answers0