Confusion with Ushort Result

consider the following code:

ushort a = 60000; a = (ushort)(a * a / a); Console.WriteLine("A = " + a); 

// This prints 53954. Why?

and

 ushort a = 40000; a = (ushort)(a * a / a); Console.WriteLine("a = " + a.ToString()); 

// This prints 40,000. How?

any help is noticeable ...

+6
source share
3 answers

Since 60000 ^ 2 is 3600000000, but the largest number that int can contain is 2 147 483 647, so it starts with -2,147,483,648.

An acceleration may contain 65,535, and then starts at 0:

For example, this prints 0:

 ushort myShort = 65535; myShort++; Console.WriteLine(myShort); //0 

It’s easier to see this if you break it down into steps:

 var B = A * A; 

This actually exceeds the capacity of int32, so it starts with -2,147,483,648, so b is -694967296 then, when you split B / A, you get: -11582, which when throws into ushort becomes 53954.

 ushort A = 60000; var B = A * A; //-694967296 var C = B / A; //-11582 ushort D = (ushort)(C); //53954 

The reason why 40,000 works is because it does not exceed int32 capacity.

 ushort A = 40000; var B = A * A; //1600000000 var C = B / A; //40000 ushort D = (ushort)(C); //40000 

uint can contain 60,000 ^ 2, so this works:

 ushort A = 60000; var B = (uint)A * A; //3600000000 var C = B / A; //60000 ushort D = (ushort)(C); //60000 

The reason C casting for ushort yeilds 53954 is because C bytes are:

 96 234 0 0 

And bytes D:

 96 234 

So they contain the same support bytes, so you get 53954 and -11582

+7
source

Since it is equivalent

A * A = -694967296 , because the result ends as int, and overflowing on short gives a bit pattern that gives this negative result. Ultimately, 60000 * 60000 cannot be saved in ushort . Add the clock to debug mode and you will see it.

Then you have

-694967296 / 60000 - which gives -11582 as an int, but when casting to ushort gives 53954 - again due to the base bit pattern.

Indeed, this code must be in the checked block, because it is for this reason that overflow errors cause massive problems.

+3
source

First good question! Now let me tell you one thing. If you try 40,000, it will work fine.

the reason is that (40,000 ^ 2) , which is the highest ushort limit, so it will convert to an integer, so it won't truncate!

If you use 60,000 , it will be! Due to limit limit!

Try with 40,000 !

I hope you get my answer

+1
source

Source: https://habr.com/ru/post/909980/


All Articles