Related Tags

c#
communitycreator

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

Theodore Kelechukwu Onyejiaku

### 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));
}
}
Getting binary equivalent of decimal numbers in C#

### 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.

RELATED TAGS

c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time