Binary digits: Difference between revisions
Content added Content deleted
(added ceylon) |
No edit summary |
||
Line 3,038: | Line 3,038: | ||
tobinary 5 |
tobinary 5 |
||
tobinary 50</lang> |
tobinary 50</lang> |
||
'=={{header|VBA}}== |
|||
'''2 ways :''' |
|||
1- Function DecToBin(ByVal Number As Long) As String |
|||
'''Arguments :''' |
|||
[Required] Number (Long) : ''should be a positive number'' |
|||
2- Function DecToBin2(ByVal Number As Long, Optional Places As Long) As String |
|||
'''Arguments :''' |
|||
[Required] Number (Long) : ''should be >= -512 And <= 511'' |
|||
[Optional] Places (Long) : ''the number of characters to use.'' |
|||
Note : If places is omitted, DecToBin2 uses the minimum number of characters necessary. |
|||
Places is useful for padding the return value with leading 0s (zeros). |
|||
<lang vb> |
|||
Option Explicit |
|||
Sub Main_Dec2bin() |
|||
Dim Nb As Long |
|||
Nb = 5 |
|||
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb) |
|||
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb) |
|||
Nb = 50 |
|||
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb) |
|||
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb) |
|||
Nb = 9000 |
|||
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb) |
|||
Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb) |
|||
End Sub |
|||
Function DecToBin(ByVal Number As Long) As String |
|||
Dim strTemp As String |
|||
Do While Number > 1 |
|||
strTemp = Number - 2 * (Number \ 2) & strTemp |
|||
Number = Number \ 2 |
|||
Loop |
|||
DecToBin = Number & strTemp |
|||
End Function |
|||
Function DecToBin2(ByVal Number As Long, Optional Places As Long) As String |
|||
If Number > 511 Then |
|||
DecToBin2 = "Error : Number is too large ! (Number must be < 511)" |
|||
ElseIf Number < -512 Then |
|||
DecToBin2 = "Error : Number is too small ! (Number must be > -512)" |
|||
Else |
|||
If Places = 0 Then |
|||
DecToBin2 = WorksheetFunction.Dec2Bin(Number) |
|||
Else |
|||
DecToBin2 = WorksheetFunction.Dec2Bin(Number, Places) |
|||
End If |
|||
End If |
|||
End Function |
|||
</lang> |
|||
[['''Output:''']] |
|||
<pre>The decimal value 5 should produce an output of : 101 |
|||
The decimal value 5 should produce an output of : 101 |
|||
The decimal value 50 should produce an output of : 110010 |
|||
The decimal value 50 should produce an output of : 110010 |
|||
The decimal value 9000 should produce an output of : 10001100101000 |
|||
The decimal value 9000 should produce an output of : Error : Number is too large ! (Number must be < 511)</pre> |
|||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |