[Professional C# 7] Signed and Unsigned Numbers (有符号数和无符号数)

To display uint and int variables in a binary form, the extension method ToBinaryString is created. 

Another extension method is AddSeparators, which adds _ separators after every four digits using LINQ methods.

public static class BinaryExtensions
{
  public static string ToBinaryString(this uint number) =>  
    Convert.ToString(number, toBase: 2).PadLeft(sizeof(uint) << 3, '0');

  public static string ToBinaryString(this int number) => 
    Convert.ToString(number, toBase: 2).PadLeft(sizeof(int) << 3, '0');

  public static string AddSeparators(this string number) =>
    string.Join('_',
      Enumerable.Range(0, number.Length / 4)
        .Select(i => number.Substring(i * 4, 4)).ToArray());
}

One important thing to remember working with binaries is that using signed types such as int, long,
short, the leftmost bit is used to represent the sign.

private static void SignedNumbers()
{
  Console.WriteLine(nameof(SignedNumbers));
  void DisplayNumber(string title, int x) =>
    Console.WriteLine($"{title,-11} " +
      $"bin: {x.ToBinaryString().AddSeparators()}, " +     
      $"dec: {x}, hex: {x:X}");
  int maxNumber = int.MaxValue;
  DisplayNumber("max int", maxNumber);
  for (int i = 0; i < 3; i++)
  {
    maxNumber++;
    DisplayNumber($"added {i + 1}", maxNumber);
  }
  Console.WriteLine();
  //...
}

With the output of the application:

max int bin: 0111_1111_1111_1111_1111_1111_1111_1111, dec: 2147483647,hex: 7FFFFFFF
added 1 bin: 1000_0000_0000_0000_0000_0000_0000_0000, dec: -2147483648,hex: 80000000
added 2 bin: 1000_0000_0000_0000_0000_0000_0000_0001, dec: -2147483647,hex: 80000001
added 3 bin: 1000_0000_0000_0000_0000_0000_0000_0010, dec: -2147483646,hex: 80000002

Adding 1 to the first output results in an overflow of the int type setting the sign bit, and all other bits are 0.

C# provides a checked operator that you can use to test whether an operation causes an arithmetic over-
flow. You can use the checked operator to confirm that a cast is safe and to force the runtime to throw an overflow exception if it is not:

(The checked and unchecked Operators)

 

posted @ 2022-08-04 16:21  FH1004322  阅读(31)  评论(0编辑  收藏  举报