A Double-Word

Introduction

A double-word is a group of two consecutive Words. This means that a double-word combines 4 bytes or 32 bits. The bits, counted from right to left, start at 0 and end at 31. The rightest bit, bit 0, is called the low order bit or LO bit or LOBIT. The most left bit, bit 31, is called the high order bit or HI bit or HIBIT. The other bits are called using their positions.

The group of the first 8 bits (from bit 0 to bit 7), which is the right byte, is called the low order byte, or LOBYTE. The group of the last 8 bits (from bit 24 to bit 31), which is the left byte, is called the high order byte, or HIBYTE. The other bytes are called by their positions. The group of the right 16 bits, or the right Word, is called the low order word, or LOWORD. The group of the left 16 bits, or the left word, is called the high order word, or HIWORD.

The minimum binary number you can represent with a double-word is 0. The minimum decimal value of a double-word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula giving a 1 value to each bit:

2n-1 230  229  228 227  226 225 224
etc 1,073,741,824 536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216
 
223 222 221 220 219 218 217 216
8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536
 
215 214 213 212 211 210 29 28
32,768 16,384 8,192 4,096 2,048 1,024 512 256
 
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1

1*231+1*230+1*229 + 1*228 + 1*227 + 1*226 + 1*225 + 1*224 + 1*223 + 1*222 + 1*221 + 1*220 + 1*219 + 1*218 + 1*217 + 1*216 + 1*215 + 1*214 + 1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20

= 2,147,483,648 + 1,073,741,824 + 536,870,912 + 268,435,456 + 134,217,728 + 67,108,864 + 33,554,432 + 16,777,216 + 8,388,608 + 4,194,304 + 2,097,152 + 1,048,576 + 524,288 + 262,144 + 131,072 + 65,536 + 32,768 + 16,384 + 8,192 + 4,096 + 2,048 + 1,024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1

= 4,286,578,708

The minimum hexadecimal value you can store in a double-word is 0x00000000000000000000000000000000 which is the same as 0x0. To find out the maximum hexadecimal number you can represent with a word, replace every group of 4-bits with an f or F:

1111 1111 1111 1111 1111 1111 1111 1111
f f f f f f f f
= 0xffffffff = 0xFFFFFFFF

To declare a variable that can hold large values, you can use the var keyword and initialize the variable with the desired value. Here is an example:

using static System.Console;

var apartNbr = 24;

WriteLine("===============================");
WriteLine("Apartment Rental Management");
WriteLine("-------------------------------");
WriteLine("Apartment #: {0}", apartNbr);
WriteLine("===============================");

This would produce:

===============================
Apartment Rental Management
-------------------------------
Apartment #: 24
===============================

Press any key to close this window . . .

Signed Integers

A double-word is large enough to contain double the amount of data that can be stored in a word. This is equivalent to 32 bits or 4 bytes or 4,294,967,295. Therefore, a double-word is used for small or large numbers.

To use a variable that would hold quite large numbers, besides the var keyword, you can declare it using the int keyword. A variable declared as int can store values between -2,147,483,648 and 2,147,484,647 negative or positive, that can fit in 32 bits.

To let you display an integer to the console screen, both the Write() and the WriteLine() methods each has a syntax that takes an int argument. Their syntaxes are:

public static void Write(int value);
public static void WriteLine(int value);

Here are examples:

using static System.Console;

int coordX = 12;
int coordY = -8;

WriteLine("=======================================");
Write("Cartesian Coordinate System: ");
WriteLine("P({0}, {1})", coordX, coordY);
WriteLine("=======================================");

When executed, the program would produce:

=======================================
Cartesian Coordinate System: P(12, -8)
=======================================

Press any key to close this window . . .

If the number is large, don't use the character for thousands separators, which in English is the comma used in the English language. Here is an example:

using static System.Console;

int yearlySalary = 82460;

WriteLine("=======================================");
WriteLine("Fun Department Store");
WriteLine("Yearly Salary: {0}", yearlySalary);
WriteLine("=======================================");

The program would produce:

=======================================
Fun Department Store
Yearly Salary: 82460
=======================================

Press any key to close this window . . .

Characteristics of Integers

Creating an Integral Value

As mentioned already, an integer is a combination of digits to represent a natural number. By default, when creating the number in a C# application, use only digits. Still, if the number is large or very large and becomes difficult to read, you can separate the thousands from right to left with underscores. Here are examples:

using static System.Console;

var emplNbr = 20_931_705;
int yearlySalary = 82_460;

WriteLine("==========================");
WriteLine("Fun Department Store");
WriteLine("--------------------------");
WriteLine("Employee #:    {0}", emplNbr);
WriteLine("Yearly Salary: {0}", yearlySalary);
WriteLine("==========================");

This would produce:

==========================
Fun Department Store
--------------------------
Employee #:    20931705
Yearly Salary: 82460
==========================

Press any key to close this window . . .

Declaring a Variant Integral Variable

If you declare an integer variable using the var keyword and initialize it with a value lower than 2,147,484,647, the compiler concludes that the memory needed to store that variable is 32 bits:

If you declare an integer variable using the var keyword and initialize it with a value lower than 2,147,484,647, the compiler concludes that the memory needed to store that variable is 32 bits

Hexadecimal Numbers

When initializing an integral variable, instead of a decimal number, you can also initialize it with a hexadecimal value whose decimal equivalent is less than 2,147,484,647. Here is an example:

using static System.Console;

var number = 0xF0488EA;

WriteLine("==========================");
WriteLine("Number: {0}", number);
WriteLine("==========================");

This would produce:

==========================
Number: 251955434
==========================

Press any key to close this window . . .

Remember that you can declare the variable using the int, the var, or the dynamic keyword. In this case, initialize the variable with a natural number Here are examples:

int score = 3907;
var feel = 95;
dynamic face = 794800;

A 32-Bit Integer

To support 32-bit integers, the .NET library provides a structure named Int32. You can use it to declare a variable. Here is an example:

int score = 3907;
var feel = 95;
dynamic face = 794800;
Int32 ambiance = 9284;

The .NET library represents the int data type with a structure named Int32.

The Int32 just like the int data type are for variables that can hold values between -2,147,483,648 and 2,147,483,647. The Int32 structure is equipped with fields and methods that use the exact same names we reviewed for the byte type. This includes the ability to parse a value et get a converted integer. That structure also allows you to get the minimum and the maximum values of a 32-bit variable. Here are examples:

using System;
using static System.Console;

WriteLine("=====================================");
WriteLine("byte integer minimum:   {0}", byte.MinValue);
WriteLine("Byte integer minimum:   {0}", Byte.MinValue);
WriteLine("-------------------------------------");
WriteLine("byte integer maximum:   {0}", byte.MaxValue);
WriteLine("Byte integer maximum:   {0}", Byte.MaxValue);
WriteLine("=====================================");
WriteLine("Short integer minimum:  {0}", short.MinValue);
WriteLine("16-bit integer minimum: {0}", Int16.MinValue);
WriteLine("-------------------------------------");
WriteLine("Short integer maximum:  {0}", short.MaxValue);
WriteLine("16-bit integer maximum: {0}", Int16.MaxValue);
WriteLine("=====================================");
WriteLine("Unsigned short minimum: {0}", ushort.MinValue);
WriteLine("Unsigned short maximum: {0}", ushort.MaxValue);
WriteLine("-------------------------------------");
WriteLine("Integer minimum:        {0}", int.MinValue);
WriteLine("Int32 minimum:          {0}", Int32.MinValue);
WriteLine("-------------------------------------");
WriteLine("Integer maximum:        {0}", int.MaxValue);
WriteLine("Int32 maximum:          {0}", Int32.MaxValue);
WriteLine("=====================================");

This would produce:

=====================================
byte integer minimum:   0
Byte integer minimum:   0
-------------------------------------
byte integer maximum:   255
Byte integer maximum:   255
=====================================
Short integer minimum:  -32768
16-bit integer minimum: -32768
-------------------------------------
Short integer maximum:  32767
16-bit integer maximum: 32767
=====================================
Unsigned short minimum: 0
Unsigned short maximum: 65535
-------------------------------------
Integer minimum:        -2147483648
Int32 minimum:          -2147483648
-------------------------------------
Integer maximum:        2147483647
Int32 maximum:          2147483647
=====================================

Press any key to close this window . . .

Converting a Value to an Integer

While the Int32 structure is equipped to parse a value and get an integral value, the static Convert class is equipped with an overloaded method that can be used to convert a value to an integer. To let you convert a value to an integer, the Convert class provides an overloaded method named to ToInt32. If the value to convert is a string, such as one of the values the user would type in, or select from, a Windows controller, use the following version:

public static int ToInt32 (string value);

The method is also equipped to consider any other type. Therefore, based on the data types we have seen so far, you can use one of the following versions of the method:

public static int ToInt32 (byte value);
public static int ToInt32 (short value);

If you don't know the type of the value you want to convert, the class offers the following version of the method:

public static int ToInt32 (object value);

In either case, pass the desired value to the method. If the method succeeds with the conversion, it would produce the integral format of the argument.

Unsigned Integers

An unsigned integer is a positive natural number that can fit in up to 32 bits of the computer memory. To let you declare a variable for such a number, the C# language provides a data type named uint. The uint keyword is used for a 32-bit positive integer that is between 0 and 4,294,967,295.

To let you display an unsigned integer to the console screen, both the Console.Write() and the Console.WriteLine() methods each has a syntax that takes a uint argument. Their syntaxes are:

public static void Write(uint value);
public static void WriteLine(uint value);

Here are examples:

using static System.Console;

uint dayOfBirth = 8;
uint monthOfBirth = 11;
uint yearOfBirth = 2022;

WriteLine("==================================");
WriteLine("Red Oak High School");
WriteLine("Student Date of Birth: {0}/{1}/{2}", monthOfBirth, dayOfBirth, yearOfBirth);
WriteLine("==================================");

This would produce:

==================================
Red Oak High School
Student Date of Birth: 11/8/2022
==================================

Press any key to close this window . . .

Once again, if the number is large, you can use the underscore to separate the thousands.

Operations on Integers

Integers support all of the four regular operations: addition, subtraction, multiplication, and division. When it comes to the division:

A Quad-Word

Introduction

To store a very large number that cannot fit in a double-word, you can consider a combination of 64 bits. The group can also be referred to as a quad-word. A quad-word is very large. It can store numbers in the range of -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807.

If you declare an integer variable using the var keyword and initialize it with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler concludes that the memory needed to store that variable is 64 bits:

If you declare an integer variable using the var keyword and initialize it with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler concludes that the memory needed to store that variable is 64 bits

Long Integers

To let you use a variable that can hold very large numbers that may require up to 64 bits, the C# language provides a data type named long. You can use it to declare a variable.

To let you display an unsigned integer to the console screen, both the Console.Write() and the Console.WriteLine() methods each has a syntax that takes a long argument. Their syntaxes are:

public static void Write(long value);
public static void WriteLine(long value);

Here is an example:

using static System.Console;

long areaSqrMiles = 3705407;

WriteLine("Country Statistics");
WriteLine("Area: " + areaSqrMiles + " Sqr Miles");
WriteLine("==========================");

This would produce:

Country Statistics
Area: 3705407 Sqr Miles
==========================

Press any key to close this window . . .

As always, you can also use the var keyword to declare the variable. When initializing the variable, don't use the official thousands separator. Instead, you can either type the number as it is or you can use the underscore(s) to separate the thousands. Here are examples:

using static System.Console;

long areaSqrMiles = 3705407;
long areaSqrKms = 9_596_961;
long population = 1_403_500_365;

WriteLine("Country Statistics");
WriteLine("------------------------------------------------");
WriteLine("Area:       {0} Sqr Kms ({1} Sqr Miles)", areaSqrKms, areaSqrMiles);
WriteLine("Population: {0}", population);
WriteLine("================================================");

This would produce:

Country Statistics
------------------------------------------------
Area:       9596961 Sqr Kms (3705407 Sqr Miles)
Population: 1403500365
================================================

Press any key to close this window . . .

As stated previously, if you initialize the variable with a value lower than 2,147,484,647, the compiler would allocate 32 bits of memory for it. If you initialize the variable with a value between 2,147,484,647 and 9,223,372,036,854,775,807, the compiler would allocate 64 bits of memory for it. If the value is higher than 9,223,372,036,854,775,807, which is too large, the compiler would present an error.

This means that you should limit the values assigned to integral variables to 64 bits, which is very significant. Here is an example:

using static System.Console;

var countryArea = 5638648;

WriteLine("Country Statistics");
WriteLine("------------------------------------------------");
WriteLine("Country Area: {0} km2", countryArea);
WriteLine("================================================");

This would produce:

Country Statistics
------------------------------------------------
Country Area: 5638648 km2
================================================

Press any key to close this window . . .

As mentioned for other integral types, you can initialize a long variable with a hexadecimal value.

Although the long data type is used for large numbers, it mainly indicates the amount of space available but you don't have to use the whole space. For example, you can use the long keyword to declare a variable that would hold the same range of numbers as the short, the int, or the uint data types. If you declare a variable as long but use it for small numbers that don't require 64 bits, the compiler would allocate the appropriate amount of space to accommodate the values of the variable. Consequently, the amount of space made available may not be as large as 64 bits. If you insist and want the compiler to reserve 64 bits, when assigning a value to the variable, add an L suffix to it. Here is an example that uses a long variable to store a number that would fit in 32 bits:

using static System.Console;

long countryArea = 5638648L;

WriteLine("Country Area: {0} km2", countryArea);
WriteLine("========================================");

This would produce:

Country Area: 5638648 km2
========================================

Press any key to close this window . . .

Therefore, keep in mind that an int, a uint, ashort, or a ushort can fit in a long variable.

.NET Long Integers

To support long integers, the .NET library provides a structure named Int64. That structure holds the characteristics of the long data type. Here are examples of accessing the minimum and the maximum values:

using System;
using static System.Console;

WriteLine("===========================================================================");
WriteLine("Byte Minimum Value (Natural):                  " + byte.MinValue.ToString());
WriteLine("Byte Minimum Value (Hexadecimal):              0x" + byte.MinValue.ToString("X"));
WriteLine("Byte Maximum Value (Natural):                  " + Byte.MaxValue.ToString());
WriteLine("Byte Maximum Value (Hexadecimal):              0x" + Byte.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Short Minimum Value (Natural):                " + short.MinValue.ToString());
WriteLine("Short Minimum Value (Natural):                " + short.MinValue.ToString("X"));
WriteLine("Short Maximum Value (Natural):                " + Int16.MaxValue.ToString());
WriteLine("Short Maximum Value (Hexadecimal):            0x" + Int16.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Unsigned Short Minimum Value (Natural):       " + ushort.MinValue.ToString());
WriteLine("Unsigned Short Minimum Value (Natural):       " + ushort.MinValue.ToString("X"));
WriteLine("Unsigned Short Maximum Value (Natural):       " + ushort.MaxValue.ToString());
WriteLine("Unsigned Short Value (Hexadecimal):           0x" + ushort.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Integer Minimum Value (Natural):              " + Int32.MinValue.ToString("N"));
WriteLine("Integer Minimum Value (Hexadecimal):          0x" + Int32.MinValue.ToString("X"));
WriteLine("Integer Maximum Value (Natural):              " + Int32.MaxValue.ToString("N"));
WriteLine("Integer Maximum Value (Hexadecimal):          0x" + Int32.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Unsigned Integer Minimum Value (Natural):     " + uint.MinValue.ToString());
WriteLine("Unsigned Integer Minimum Value (Hexadecimal): 0x" + uint.MinValue.ToString("X"));
WriteLine("Unsigned Integer Maximum Value (Natural):     " + uint.MaxValue.ToString("N"));
WriteLine("Unsigned Integer Value (Hexadecimal):         0x" + uint.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Long Minimum Value (Natural):                 " + long.MinValue.ToString("N"));
WriteLine("Long Minimum Value (Hexadecimal):             0x" + long.MinValue.ToString("X"));
WriteLine("Long Maximum Value (Natural):                 " + long.MaxValue.ToString("N"));
WriteLine("Long Maximum Value (Hexadecimal):             0x" + long.MaxValue.ToString("X"));
WriteLine("============================================================================");

This would produce:

===========================================================================
Byte Minimum Value (Natural):                  0
Byte Minimum Value (Hexadecimal):              0x0
Byte Maximum Value (Natural):                  255
Byte Maximum Value (Hexadecimal):              0xFF
----------------------------------------------------------------------------
Short Minimum Value (Natural):                -32768
Short Minimum Value (Natural):                8000
Short Maximum Value (Natural):                32767
Short Maximum Value (Hexadecimal):            0x7FFF
----------------------------------------------------------------------------
Unsigned Short Minimum Value (Natural):       0
Unsigned Short Minimum Value (Natural):       0
Unsigned Short Maximum Value (Natural):       65535
Unsigned Short Value (Hexadecimal):           0xFFFF
----------------------------------------------------------------------------
Integer Minimum Value (Natural):              -2,147,483,648.00
Integer Minimum Value (Hexadecimal):          0x80000000
Integer Maximum Value (Natural):              2,147,483,647.00
Integer Maximum Value (Hexadecimal):          0x7FFFFFFF
----------------------------------------------------------------------------
Unsigned Integer Minimum Value (Natural):     0
Unsigned Integer Minimum Value (Hexadecimal): 0x0
Unsigned Integer Maximum Value (Natural):     4,294,967,295.00
Unsigned Integer Value (Hexadecimal):         0xFFFFFFFF
----------------------------------------------------------------------------
Long Minimum Value (Natural):                 -9,223,372,036,854,775,808.00
Long Minimum Value (Hexadecimal):             0x8000000000000000
Long Maximum Value (Natural):                 9,223,372,036,854,775,807.00
Long Maximum Value (Hexadecimal):             0x7FFFFFFFFFFFFFFF
============================================================================

Press any key to close this window . . .

Unsigned Long Integers

You can use a combination of 64 bits to store positive or negative integers. In some cases, you will need a variable to hold only positive, though large, numbers. To declare such a variable, you can use the ulong data type. A variable declared as ulong can handle extremely positive numbers that range from 0 to 18,446,744,073,709,551,615 to fit in 64 bits.

To let you display an unsigned long integer to the console screen, both the Console.Write() and the Console.WriteLine() methods each has a syntax that takes a long argument. Their syntaxes are:

public static void Write(ulong value);
public static void WriteLine(ulong value);

Here is an example of accessing the minimum and the maximum values of an unsigned long integer:

using System;
using static System.Console;

WriteLine("===========================================================================");
WriteLine("Byte Minimum Value (Natural):                  " + byte.MinValue.ToString());
WriteLine("Byte Minimum Value (Hexadecimal):              0x" + byte.MinValue.ToString("X"));
WriteLine("Byte Maximum Value (Natural):                  " + Byte.MaxValue.ToString());
WriteLine("Byte Maximum Value (Hexadecimal):              0x" + Byte.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Short Minimum Value (Natural):                " + short.MinValue.ToString());
WriteLine("Short Minimum Value (Natural):                " + short.MinValue.ToString("X"));
WriteLine("Short Maximum Value (Natural):                " + Int16.MaxValue.ToString());
WriteLine("Short Maximum Value (Hexadecimal):            0x" + Int16.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Unsigned Short Minimum Value (Natural):       " + ushort.MinValue.ToString());
WriteLine("Unsigned Short Minimum Value (Natural):       " + ushort.MinValue.ToString("X"));
WriteLine("Unsigned Short Maximum Value (Natural):       " + ushort.MaxValue.ToString());
WriteLine("Unsigned Short Value (Hexadecimal):           0x" + ushort.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Integer Minimum Value (Natural):              " + Int32.MinValue.ToString("N"));
WriteLine("Integer Minimum Value (Hexadecimal):          0x" + Int32.MinValue.ToString("X"));
WriteLine("Integer Maximum Value (Natural):              " + Int32.MaxValue.ToString("N"));
WriteLine("Integer Maximum Value (Hexadecimal):          0x" + Int32.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Unsigned Integer Minimum Value (Natural):     " + uint.MinValue.ToString());
WriteLine("Unsigned Integer Minimum Value (Hexadecimal): 0x" + uint.MinValue.ToString("X"));
WriteLine("Unsigned Integer Maximum Value (Natural):     " + uint.MaxValue.ToString("N"));
WriteLine("Unsigned Integer Value (Hexadecimal):         0x" + uint.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Long Minimum Value (Natural):                 " + long.MinValue.ToString("N"));
WriteLine("Long Minimum Value (Hexadecimal):             0x" + long.MinValue.ToString("X"));
WriteLine("Long Maximum Value (Natural):                 " + long.MaxValue.ToString("N"));
WriteLine("Long Maximum Value (Hexadecimal):             0x" + long.MaxValue.ToString("X"));
WriteLine("----------------------------------------------------------------------------");
WriteLine("Unsigned Long Minimum Value (Natural):          " + ulong.MinValue.ToString("N"));
WriteLine("Unsigned Long Minimum Value (Hexadecimal):    0x" + ulong.MinValue.ToString("X"));
WriteLine("Unsigned Long Maximum Value (Natural):          " + ulong.MaxValue.ToString("N"));
WriteLine("Unsigned Long Maximum Value (Hexadecimal):    0x" + ulong.MaxValue.ToString("X"));
WriteLine("============================================================================");

This would produce:

===========================================================================
Byte Minimum Value (Natural):                  0
Byte Minimum Value (Hexadecimal):              0x0
Byte Maximum Value (Natural):                  255
Byte Maximum Value (Hexadecimal):              0xFF
----------------------------------------------------------------------------
Short Minimum Value (Natural):                -32768
Short Minimum Value (Natural):                8000
Short Maximum Value (Natural):                32767
Short Maximum Value (Hexadecimal):            0x7FFF
----------------------------------------------------------------------------
Unsigned Short Minimum Value (Natural):       0
Unsigned Short Minimum Value (Natural):       0
Unsigned Short Maximum Value (Natural):       65535
Unsigned Short Value (Hexadecimal):           0xFFFF
----------------------------------------------------------------------------
Integer Minimum Value (Natural):              -2,147,483,648.00
Integer Minimum Value (Hexadecimal):          0x80000000
Integer Maximum Value (Natural):              2,147,483,647.00
Integer Maximum Value (Hexadecimal):          0x7FFFFFFF
----------------------------------------------------------------------------
Unsigned Integer Minimum Value (Natural):     0
Unsigned Integer Minimum Value (Hexadecimal): 0x0
Unsigned Integer Maximum Value (Natural):     4,294,967,295.00
Unsigned Integer Value (Hexadecimal):         0xFFFFFFFF
----------------------------------------------------------------------------
Long Minimum Value (Natural):                 -9,223,372,036,854,775,808.00
Long Minimum Value (Hexadecimal):             0x8000000000000000
Long Maximum Value (Natural):                 9,223,372,036,854,775,807.00
Long Maximum Value (Hexadecimal):             0x7FFFFFFFFFFFFFFF
----------------------------------------------------------------------------
Unsigned Long Minimum Value (Natural):        0.00
Unsigned Long Minimum Value (Hexadecimal):    0x0
Unsigned Long Maximum Value (Natural):        18,446,744,073,709,551,615.00
Unsigned Long Maximum Value (Hexadecimal):    0xFFFFFFFFFFFFFFFF
============================================================================

Press any key to close this window . . .

Floating-Point Numbers

Introduction to Real Numbers

A real number is a number that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel:

Regional

On both sides of the decimal symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.

Both Microsoft Windows and .NET library provides various levels of support for real numbers.

Introduction to Floating-Point Numbers

The integers we have used so far have the main limitation of not allowing decimal values. C# provides floating values that would solve this problem. The most fundamental data type you can use for a floating-point number is called float. A variable declared as float can store real numbers that range from 3.402823e38 to 3.402823e38 in 32 bits. Here is an example:

float distance;

To let you display a floating-point number with single-precision to the console screen, both the Console.Write() and the Console.WriteLine() methods each has a syntax that takes a float argument. Their syntaxes are:

public static void Write(object value);
public static void WriteLine(object value);

A Number with Single-Precision

As seen with integers, to support real numbers, the .NET library provides various structures. All the structures are created in the System namespace.

To support numbers with single-precision, the .NET library provides a structure named Single. The Single structure is used to support the float data type of the C# language. This means that the characteristics of the float data type are defined in the Single structure. All the characteristics of we reviewed for the structures associated with integers are also available for real numbers. This includes the ability to display a value by calling one of the versions of the overloaded ToString() methods that every number-associated structure is equipped with. The operations also include the ability to parse or to to try parsing a value to produce an appropriate real number.

Characteristics of Floating-Point Numbers

The Minimum Value of a Type

Like integers, floating-point numbers have limits so they can fit in the computer memory allocated for them. As seen for the structures of integers, to let you get the lowest value that a type can hold, each number-associated structure is equipped with a constant field named MinValue. For the float and Single type, this field is defined as follows:

public const float MinValue = -3.40282347E+38;

To get the lowest value of a type, you can access this field. Here is an example:

using static System.Console;

WriteLine("===========================================================================================");
WriteLine("Float Minimum Value (Natural):     " + float.MinValue.ToString("N"));
WriteLine("Float Minimum Value (Exponential): " + float.MinValue.ToString("E"));
WriteLine("===========================================================================================");

This would produce:

===========================================================================================
Float Minimum Value (Natural):     -340,282,346,638,528,859,811,704,183,484,516,925,440.00
Float Minimum Value (Exponential): -3.402823E+038
===========================================================================================

Press any key to close this window . . .

The Maximum Value of a Type

To let you get the highest value that a floating-point number can hold, their structure is equipped with a constant field named MaxValue. For the float type, this field is defined as follows:

public const float MaxValue = 3.40282347E+38;

To get the highest value of a type, access this field. Here is an example:

using static System.Console;

WriteLine("===========================================================================================");
WriteLine("Float Minimum Value (Natural):     " + float.MinValue.ToString("N"));
WriteLine("Float Minimum Value (Exponential): " + float.MinValue.ToString("E"));
WriteLine("Float Maximum Value (Natural):     " + float.MaxValue.ToString("N"));
WriteLine("Float Maximum Value (Exponential): " + float.MaxValue.ToString("E"));
WriteLine("===========================================================================================");

This would produce:

===========================================================================================
Float Minimum Value (Natural):     -340,282,346,638,528,859,811,704,183,484,516,925,440.00
Float Minimum Value (Exponential): -3.402823E+038
Float Maximum Value (Natural):     340,282,346,638,528,859,811,704,183,484,516,925,440.00
Float Maximum Value (Exponential): 3.402823E+038
===========================================================================================

Press any key to close this window . . .

When the Value is Not-A-Number

After declaring and initializing a float (or a Single) variable, it should hold an appropriate value. If you get the variable value some other way, at one time or another, you may not know what value is stored in the memory allocated for the variable. In fact, the variable may hold a value that is not a number. To let you check whether the variable is holding a value that is not a number, the Single structure of the floating-point type is equipped with a constant named NaN. To get its information, type the float data type, followed by the period operator, and followed by the NaN constant. Here is an example:

using static System.Console;

floatnumber = 0D;

if( number == double.NaN )
    WriteLine("The value is not a number.");

Another technique you can use to check this characteristic is to call the IsNaN() method is the Single structure.

The Epsilon Constant

Using one integer and one floating-point number, or with two floating-point numbers, you can perform one of the routine arithmetic operations such as the addition, the subtraction, the multiplication, or the division. When it comes to the division and if performed on two constants, you can get a positive or a negative number. In highly precise calculations, you may have to deal with an approximate number whose exact value is not known. For example, the smallest positive number is called epsilon. In the Single structure, this constant is named Epsilon. For the single-precision type, the epsilon is equal to 1.445.

The Negative Infinity

When dealing with real numbers, some operations produce very little or very large numbers. In algebra, the smallest conceptual number is called negative infinity (in reality, infinity is not a number but a concept). In the .NET library, the negative infinity is represented by a constant named NegativeInfinity. To access this number, type float, followed by a period operator, followed by the name of this constant.

To let you find out whether a variable holds a negative infinity value, the structures of the floating-point number is equipped with a method named IsNegativeInfinity. The syntax of this method is:

public static bool IsNegativeInfinity(float f);

The Positive Infinity

On the other extreme, the possible largest number is named positive infinity. This constant is represented in the .NET library by the PositiveInfinity value. To access this constant, type float, a period, and this constant. To find out if a variable's value is a positive infinity, you can call its IsPositiveInfinity() method. The syntax of this method ise:

public static bool IsPositiveInfinity(float f);

To check whether the value of a variable is one of the infinities, you can call its IsInfinity() method. The syntax of this method is:

public static bool IsInfinity(float f);

Double-Precision Numbers

Introduction

When a variable is larger than the float can handle and requires more precision, you should declare it using either the var or the double keyword.

To let you display a floating-point number with double-precision to the console screen, both the Console.Write() and the Console.WriteLine() methods each has a syntax that takes a double argument. Their syntaxes are:

public static void Write(double value);
public static void WriteLine(double value);

Here is an example:

using static System.Console;

var number = 62834.9023;

WriteLine("Number: " + number);

This would produce:

Number: 62834.9023
Press any key to close this window . . .

A variable declared as double uses 64 bits to store very large numbers ranging from 1.79769313486232e308 to 1.79769313486232e308 with a precision of 15 or 16 digits.

A Double-Precision Number

To support numbers with double-precision, the .NET library provides a structure named Double. This structure is equipped with the same members as the Single structure. These include the minimum and the maximum values. Here are examples:

using static System.Console;

WriteLine("===========================================================================================");
WriteLine("Float Minimum Value (Natural):     " + float.MinValue.ToString("N"));
WriteLine("Float Minimum Value (Exponential): " + float.MinValue.ToString("E"));
WriteLine("Float Maximum Value (Natural):     " + float.MaxValue.ToString("N"));
WriteLine("Float Maximum Value (Exponential): " + float.MaxValue.ToString("E"));
WriteLine("-------------------------------------------------------------------------------------------");
WriteLine("Double Minimum Value (Natural):     " + double.MinValue.ToString("N"));
WriteLine("Double Minimum Value (Exponential): " + double.MinValue.ToString("E"));
WriteLine("Double Maximum Value (Natural):     " + double.MaxValue.ToString("N"));
WriteLine("Double Maximum Value (Exponential): " + double.MaxValue.ToString("E"));
WriteLine("===========================================================================================");

This would produce:

===========================================================================================
Float Minimum Value (Natural):     -340,282,346,638,528,859,811,704,183,484,516,925,440.00
Float Minimum Value (Exponential): -3.402823E+038
Float Maximum Value (Natural):     340,282,346,638,528,859,811,704,183,484,516,925,440.00
Float Maximum Value (Exponential): 3.402823E+038
-------------------------------------------------------------------------------------------
Double Minimum Value (Natural):     -179,769,313,486,231,570,814,527,423,731,704,356,798,070,567,525,844,996,598,917,476,803,157,260,780,028,538,760,589,558,632,766,878,171,540,458,953,514,382,464,234,321,326,889,464,182,768,467,546,703,537,516,986,049,910,576,551,282,076,245,490,090,389,328,944,075,868,508,455,133,942,304,583,236,903,222,948,165,808,559,332,123,348,274,797,826,204,144,723,168,738,177,180,919,299,881,250,404,026,184,124,858,368.00
Double Minimum Value (Exponential): -1.797693E+308
Double Maximum Value (Natural):     179,769,313,486,231,570,814,527,423,731,704,356,798,070,567,525,844,996,598,917,476,803,157,260,780,028,538,760,589,558,632,766,878,171,540,458,953,514,382,464,234,321,326,889,464,182,768,467,546,703,537,516,986,049,910,576,551,282,076,245,490,090,389,328,944,075,868,508,455,133,942,304,583,236,903,222,948,165,808,559,332,123,348,274,797,826,204,144,723,168,738,177,180,919,299,881,250,404,026,184,124,858,368.00
Double Maximum Value (Exponential): 1.797693E+308
===========================================================================================

Press any key to close this window . . .

Characteristics of a Double-Precision Value

The Epsilon Constant

The double data type uses the same characteristics we reviewed for the float data type and its accompanying Single structure. The members of their structures are the same, Only some values are different. As we saw, the smallest positive number is the epsilon. For a double-precision type, the epsilon constant is equivalent to 4.94065645841247-324.

A Better Floating-Point Number

Because the double data type provides a better result with better precision than the float, whenever you declare a variable using either the var or the float keyword and assign it a value, the compiler allocates 64 bits to store the values of the variable. If you insist on the variable being treated as float, when assigning it a value, add an f or an F suffix to the value. Here is an example:

using static System.Console;

float distance = 248.38F;

WriteLine("Distance: " + distance + " km");
WriteLine("========================");

This would produce:

Distance: 248.38 km
========================

Press any key to close this window . . .

This would produce:

Distance = 248.38km

Remember that if you declare the variable as var and want to treat it as a value with single precision, add an f or an F suffix to the value assigned to it. Here is an example:

using static System.Console;

var number = 62834.9023F;

WriteLine("Number: " + number);
WriteLine("========================");

This would produce:

Number: 62834.902
========================

Press any key to close this window . . .

On the other hand, if you want a value to be treated with double-precision, add a d or a D suffix to it. Here is an example:

using static System.Console;

var number = 62834.9023D;

WriteLine("Number: " + number);
WriteLine("========================");

This would produce:

Number: 62834.9023
========================

Press any key to close this window . . .

A Decimal Number

Introduction

To support small to extremely large numbers, the C# language provides a data type named decimal. Use that keyword to declare a variable that would hold significantly large values that can be stored in a combination of 128 bits. The values stored in a decimal variable can range from -79,228,162,514,264,337,593,543,950,335 to 79,228,162,514,264,337,593,543,950,335.

Initializing a Decimal

After declaring a decimal variable, you can initialize it with a natural number. To indicate that the variable holds a decimal value, when initializing it, add an m or an M suffix to its value.

To let you display a decimal number to the console screen, both the Console.Write() and the Console.WriteLine() methods each has a syntax that takes a decimal argument. Their syntaxes are:

public static void Write(decimal value);
public static void WriteLine(decimal value);

Here is an example:

using static System.Console;

decimal hourlySalary = 24.25M;

WriteLine("Hourly Salary = {0}", hourlySalary);
WriteLine("========================");

This would produce:

Hourly Salary = 24.25
========================

Press any key to close this window . . .

Decimal Number Support

To support numeric values with high precision, the .NET library provides a structure named Decimal. This structure provides the characteristics of the C#'s decimal type. The structure has the same members we reviewed for the Single and the Double structures.

Distinguishing the Floating-Point Variables

As seen in previous sections and this one, when declaring and initializing a real variable, the suffix you give to its assigned value indicates to the compiler the actual type of value and the type of memory that would be allocated for the variable:

Consider the following program:

using static System.Console;

Write("560 / 672 = ");
WriteLine(560 / 672);

The purpose of this program is to get the division of 560 by 672. This would produce:

560 / 672 = 0
Press any key to close this window . . .

Notice that, when such numbers are submitted to the program, the compiler decides that these are integers and the result produces 0. If you write such an equation and want the result to appear as a real number, you must explicitly indicate it to the compiler. One way you can do this consists of adding decimal places to at least one of the numbers. Here is an example:

using static System.Console;

WriteLine("560 / 672 = {0}", 560.00 / 672.00);
WriteLine("===============================");

This time, the compiler will conclude that the value is a floating-point number; but which one? By default, the compiler would apply the double data type. This version of the program would produce:

560 / 672 = 0.8333333333333334
===============================

Press any key to close this window . . .

If you want to indicate that the value is a float, a double, or a decimal, add the appropriate prefix to it: f, F, d, D, m, or M. Here are examples:

using static System.Console;

WriteLine("560 / 672 = {0}", 560F / 672f);
WriteLine("================================================");

This version of the program would produce:

560 / 672 = 0.8333333
================================================

Press any key to close this window . . .

The Boolean Type

Introduction

As seen in previous lessons, the bool data type is used to represent a value considered as being true or false. In the .NET library, the bool data type is represented by a structure named Boolean. The true value of a bool variable is represented by a field named TrueString. The false value is represented by a field named FalseString. In other words, when true (or false) is represented as a string, "true" (or "false") is the same as TrueString (or FalseString).

Parsing a Boolean Variable

You can retrieve the value of a Boolean variable from a user. To support this, the Boolean structure is equipped with a static method named Parse. The Boolean.Parse() method is declared as follows:

public static bool Parse(string value);

This method takes as argument a string. The argument must contain either the word True or the word False (case-insensitive in both cases). If the argument is passed as "True", the method returns true. If the argument is "false", this method returns false.

When calling the Boolean.Parse() method to retrieve the value of a Boolean variable, if the supplied value is "True" or "False", the compiler would process it. If the value is not valid, the program would produce an error.

To avoid the error, the Boolean structure provides the TryParse() method. Its syntax is:

public static bool TryParse(string value, out bool result);

The first argument is the value to be parsed. If that value is valid, the second argument holds the True or False value of the first.

Consider the following code:

bool alt;
bool HouseHas3Bedrooms = bool.TryParse("False", out alt);

The first argument returns True although it was passed as False. This means that, if the value of the first argument is valid, it is the second argument, not the first, that holds the result. If the first argument is not valid, the second argument returns a False value. Consider the following version of the program:

bool alt;
bool HouseHas3Bedrooms = bool.TryParse("Don't Know", out alt);

The Default Value of a Type

Introduction

In previous sections, we saw that each data type has a range of value from one minimum to a maximum. In the same way, every type has a default value. For an integer, the default value is 0. For a decimal type, the default value is 0.00. To get the default value of a type, you can use a keyword named default. When declaring a variable of a primitive type, if you want it to hold a default value based on its type, assign the default keyword to it. Here are examples:

using static System.Console;

byte bits = default;
short small = default;
int natural = default;
float single = default;
double dbl = default;
decimal dec = default;

WriteLine("Default Values");
WriteLine("-----------------------");
WriteLine("Byte Integer:     {0}", bits);
WriteLine("Small Integer:    {0}", small);
WriteLine("Natural Number:   {0}", natural);
WriteLine("Single Precision: {0}", single);
WriteLine("Double Precision: {0}", dbl);
WriteLine("Decimal Number:   {0}", dec);
WriteLine("=======================");

This would produce:

Default Values
-----------------------
Byte Integer:     0
Small Integer:    0
Natural Number:   0
Single Precision: 0
Double Precision: 0
Decimal Number:   0
=======================

Press any key to close this window . . .

Selecting the Default Value

In the above examples, we let the compiler use the default value of the variable we were declaring. In some cases, you may want the value to hold the default value of a different data type. To do this, you can use an operator named default. It is used as a function. Its syntax is:

value-type default(data-type);

Write the default operator and apply some parentheses to it. In the parentheses, write the data type whose default value you want to access. You can assign the expression to a variable. If you are declaring the variable using either the var or the dynamic keyword, you can pass any type to the default() operator. If you declare the variable using a known type, the size of the data type passed to the default() operator must be equal or less than that of the type of the variable. Here are examples:

using static System.Console;

var bits = default(decimal);
dynamic small = default(double);
int natural = default(short);
float single = default(byte);
double dbl = default(short);
decimal dec = default(int);

WriteLine("Default Values");
WriteLine("-----------------------");
WriteLine("Byte Integer:     {0}", bits);
WriteLine("Small Integer:    {0}", small);
WriteLine("Natural Number:   {0}", natural);
WriteLine("Single Precision: {0}", single);
WriteLine("Double Precision: {0}", dbl);
WriteLine("Decimal Number:   {0}", dec);
WriteLine("=======================");

This would produce:

Default Values
-----------------------
Byte Integer:     0
Small Integer:    0
Natural Number:   0
Single Precision: 0
Double Precision: 0
Decimal Number:   0
=======================

Press any key to close this window . . .

The Defualt Value of an Object

Like a regular variable, an object (a variable declared from a class or structure) has a default type. Normally, the default value of an object is null. To make a declared object hold a default value, assign the default operator to the object. This is also valid for strings and object variable. Here are examples:

using static System.Console;

var bits = default(decimal);
dynamic small = default(double);
int natural = default(short);
float single = default(byte);
double dbl = default(short);
decimal dec = default(int);
string? something = default;
object? obj = default;
House? prop = default;

WriteLine("Default Values");
WriteLine("-----------------------");
WriteLine("Byte Integer:     {0}", bits);
WriteLine("Small Integer:    {0}", small);
WriteLine("Natural Number:   {0}", natural);
WriteLine("Single Precision: {0}", single);
WriteLine("Double Precision: {0}", dbl);
WriteLine("Decimal Number:   {0}", dec);
WriteLine("-----------------------");
WriteLine("String:           {0}", something);
WriteLine("Object:           {0}", obj);
WriteLine("House:            {0}", prop);
WriteLine("=======================");

public class House
{
    public int Bedrooms { get; set; }
    public float Bathrooms { get; set; }
    public double MarketValue { get; set; }
}

This would produce:

Default Values
-----------------------
Byte Integer:     0
Small Integer:    0
Natural Number:   0
Single Precision: 0
Double Precision: 0
Decimal Number:   0
-----------------------
String:
Object:
House:
=======================

Press any key to close this window . . .

Setting the Default Value of a Property

We already know that, when you have created a class, before using it in a program, you must initialize its object. One way to do this is to assign a value to its property. We saw that another or better way to take care of this issue is to assign a value to each property when creating the class. Here is an example:

using static System.Console;

House? property = new();

WriteLine("House Values");
WriteLine("-----------------------");
WriteLine("Bedrooms:     {0}", property.Bedrooms);
WriteLine("Bathrooms:    {0}", property.Bathrooms);
WriteLine("Market Value: {0}", property.MarketValue);
WriteLine("=======================");

public class House
{
    public int Bedrooms { get; set; } = 3;
    public float Bathrooms { get; set; } = 2.5f;
    public double MarketValue { get; set; } = 366_580;
}

This would produce:

House Values
-----------------------
Bedrooms:     3
Bathrooms:    2.5
Market Value: 366580
=======================

Press any key to close this window . . .

The above example supposes that you know from the begining the values you want the properties to hold. In some cases you don't know or don't have those initial values. To still make sure that a property has an initial value, you can assign it the default operator when creating the class. Here are examples:

using static System.Console;

House? property = new();

WriteLine("House Values");
WriteLine("-----------------------");
WriteLine("Bedrooms:     {0}", property.Bedrooms);
WriteLine("Bathrooms:    {0}", property.Bathrooms);
WriteLine("Market Value: {0}", property.MarketValue);
WriteLine("=======================");

public class House
{
    public int Bedrooms { get; set; } = default;
    public float Bathrooms { get; set; } = default;
    public double MarketValue { get; set; } = default;
}

This would produce:

House Values
-----------------------
Bedrooms:     0
Bathrooms:    0
Market Value: 0
=======================

Press any key to close this window . . .

Previous Copyright © 2001-2023, FunctionX Friday 26 November 2021 Next