How to get the binary equivalent of a decimal number in C#

Overview

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.

Syntax

public static int[] GetBits (decimal d);

Parameters

  • decimal d: A mandatory decimal number.

Return value

This method returns an integer array that contains four elements that are the binary representation of d.

Example

// use System
using System;
// create class
class GetDecimalBytes
{
static void PrintArray(int[] array){
for (int index = 0; index < 4; index += 1)
{
Console.WriteLine(array[index]);
}
}
// main method
static void Main()
{
// create decimal values
decimal decimalNumberOne = 21.34m;
decimal decimalNumberTwo = 34.567m;
decimal decimalNumberThree = 0.1m;
// get binary equivalents
Console.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));
}
}

Explanation

  • Lines 16 to 18: We create decimal numbers.
  • Lines 22, 25, and 28: We call the 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.

Free Resources