0

By using that statement I can change my binary value to decimal value by swapping the values but why isn't this statement working for decimal to binary conversion?

int decimalVal = 10;
int binaryVal = Convert.ToInt32(decimalVal, 2); // want 1010
Aimery
  • 1,559
  • 1
  • 19
  • 24

3 Answers3

2

You should use Convert.ToInt32(String, Int32) method to convert binary to integer and Convert.ToString(Int32, Int32) method to convert integer to binary.

string binaryVal = Convert.ToString(decimalVal, 2);

To find more information:

https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=netframework-4.8

https://learn.microsoft.com/en-us/dotnet/api/system.convert.tostring?view=netframework-4.8

1

They are of different byte sizes: https://condor.depaul.edu/sjost/nwdp/notes/cs1/CSDatatypes.htm And you are trying to convert one directly and expect binary while this does not work like that.

This two answers should help you: How do I convert a decimal to an int in C#?

And

Convert integer to binary in C#

What you will figure out from this two answers is that Covnert.ToInt32 does not have an overload that takes an instance of decimal and converts it to binary. You will need to cast the decimal first to an integer and then you would be able to cast it to binary, For example:

decimal value = 8;
int n = Convert.ToInt32(value);

string binary = Convert.ToString(n, 2);
binary.Dump();

The output would be: 1000

This example is tested in Linqpad

vsarunov
  • 1,433
  • 14
  • 26
1
int decimalVal = 10;
string binary = Convert.ToString(decimalVal, 2);
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Syafiqur__
  • 531
  • 7
  • 15