We can use the GetBits()
method to get the binary equivalent or representation of a decimal number in C#. This method takes a decimal value as a parameter and returns its binary representation.
public static int[] GetBits (decimal d);
decimal d
: A mandatory decimal number.This method returns an integer array that contains four elements that are the binary representation of d
.
// use Systemusing System;// create classclass GetDecimalBytes{static void PrintArray(int[] array){for (int index = 0; index < 4; index += 1){Console.WriteLine(array[index]);}}// main methodstatic void Main(){// create decimal valuesdecimal decimalNumberOne = 21.34m;decimal decimalNumberTwo = 34.567m;decimal decimalNumberThree = 0.1m;// get binary equivalentsConsole.WriteLine("34.567 in Bytes is");PrintArray(Decimal.GetBits(decimalNumberOne));Console.WriteLine("\n34.567 in Bytes is");PrintArray(Decimal.GetBits(decimalNumberTwo));Console.WriteLine("\n34.567 in Bytes is");PrintArray(Decimal.GetBits(decimalNumberThree));}}
GetBits()
method on the decimal numbers that we created. We pass the array to the PrintArray()
method from line 6 to line 11 by using a for
loop to print out our results. The printed values are the four elements that are returned for each array.