15,935,728 members
See more:
Hi everybody

I am looking for a function to convert an int to a binary.

For example the function gets integer 23 as input and returns int(or long int) 10111 as output. Any sugestions?
Posted
JF2015 28-Oct-10 12:44pm
Binary is just a representation of an integer number. This means it doesn't matter for your long if you think of it as decimal or binary. It is just necessary if you want to output the value to the user.

Solution 3

http://www.gidforums.com/t-18481.htm[^]

basically,
it is done like this as described in the link :

C#
`string binaryValue=Convert.ToString(23,2);`

v2
JF2015 28-Oct-10 12:47pm
Tarun.K.S 28-Oct-10 12:48pm
oh i apologize! honestly i didn't see it.
Tarun.K.S 28-Oct-10 12:49pm
JF2015 28-Oct-10 12:51pm
No problem, i didn't want to be offending :)

Solution 1

Here it is:
```int myValue = 23;
string strBinary = Convert.ToString(myValue, 2);```

v2
cs101000 28-Oct-10 12:40pm
No! this will convert it to a string. As I mentioned I want it in long datatype.
Tarun.K.S 28-Oct-10 12:54pm
my vote of 5. perfect and easy answer!
Chris Trelawny-Ross 28-Oct-10 14:25pm
Sure, it will convert it to a string. Now do int.Parse(theString) to get the string as an int.

Solution 2

From - Binary to Integer
```Private Function ToInteger(ByVal x As Long) As String
Dim temp As String
Dim ch As Char
Dim multiply As Integer = 1
Dim subtract As Integer = 1
Dim len As Integer = CStr(x).Length
For Each ch In CStr(x)
For len = 1 To CStr(x).Length - subtract
multiply = multiply * 2
Next
multiply = CInt(ch.ToString) * multiply
temp = multiply + temp
subtract = subtract + 1
multiply = 1
Next
Return temp
End Function```

From - Integer to Binary
```Private Function ToBinary(ByVal x As Long) As String
Dim temp As String = ""
Do
If x Mod 2 Then
temp = "1" + temp
Else
temp = "0" + temp
End If
x = x \ 2
If x < 1 Then Exit Do
Loop
Return temp
End Function```
You can add this function to your application and call it with passing the respective parameter.

JF2015 28-Oct-10 12:46pm
Bit too compicated for .Net and written in VB, not as desired in c#. But, good to show how its done :)
cs101000 28-Oct-10 12:46pm
In which language the code is?
Tarun.K.S 28-Oct-10 12:58pm
its in Visual Basic.
ShashankSinghThakur 28-Oct-10 13:10pm
u can convert to vb.net to c# see below link
http://www.developerfusion.com/tools/convert/csharp-to-vb/
Rajesh Anuhya 29-Oct-10 6:58am
too complicated.., take much time to execute..