markjprice / cs12dotnet8

Repository for the Packt Publishing book titled "C# 12 and .NET 8 - Modern Cross-Platform Development Fundamentals" by Mark J. Price
564 stars 164 forks source link

Chapter 3, page 149 #38

Closed m-ngr closed 3 months ago

m-ngr commented 3 months ago

Hi Mark, At page 149, the book says: "That is why when you have an integer too large to fit in a 32-bit integer, it becomes -1."

image

It's not always the case that the result of this type of casting is -1. When casting from a wider integer data type to a narrower integer data type, the most significant extra bits gets truncated and the least significant bits represents the result of the casting.

For example:

long x = 0b_101000101010001100100111010100101010;
int y = (int) x;

Console.WriteLine($"{x,64:B64} = {x}");
Console.WriteLine($"{y,64:B32} = {y}");

the result:

0000000000000000000000000000101000101010001100100111010100101010 = 43657622826
                                00101010001100100111010100101010 = 707949866
markjprice commented 3 months ago

Thank you. You're right. I've added this to the errata: https://github.com/markjprice/cs12dotnet8/blob/main/docs/errata/errata.md#page-149---how-negative-numbers-are-represented-in-binary