Android Code Snippet BooleanConv

SubName: BooleanConv.

Descriptions:
Converts a Boolean to an Int or vice-versa
Return value: Object: Int(0 or 1) if Value is a Boolean - Boolean(False or True) if Value is an Int

B4X:
Public Sub BooleanConv(Value As Object) As Object
   Dim Result As Object = 0
 
   If GetType(Value) = "java.lang.Integer" Then
     Dim b As Boolean = (Value = 1)
     Result = b
   Else ' value should be a boolean
     If Value = True Then
       Result = 1
     End If
   End If
 
   Return Result
End Sub


Example:
B4X:
Dim Bool As Boolean
Bool = False
Log("conv Bool = False: " & BooleanConv(Bool))
Bool = True
Log("conv Bool = True: " & BooleanConv(Bool))

Dim Integer As Int
Integer = 0
Log("conv Integer = 0: " & BooleanConv(Integer))
Integer = 1
Log("conv Integer = 1: " & BooleanConv(Integer))

LOG:
conv Bool = False: 0
conv Bool = True: 1
conv Integer = 0: false
conv Integer = 1: true


NOTE:
Sorry, I know that it isn't exactly the "silver bullet" :D but it can be useful


Tags: Boolean, Convert, Conversion
 
Last edited:

wonder

Expert
Licensed User
Longtime User
Why not just:
B4X:
Sub Bool2Int(value as Boolean) as Int
    If value Then Return 1
    Return 0
End Sub

Sub Int2Bool(value as Int) as Boolean
    If value = 0 Then Return False
    Return True
End Sub

:)
 

wonder

Expert
Licensed User
Longtime User
Your method is fine Luca. :) However, in a performance critical application (games, physics, simulations) the creation and destruction of a Java Object is a more expensive operation than simply dealing with primitive types.
 

MaFu

Well-Known Member
Licensed User
Longtime User
No, because you should pass 1 or 0 only (checks are not performed in the routine, but it is a simple little thing that has a simple purpose).
Maybe. In this case it doesn't matter, so why not use "Value <> 0" and use the safety way.
 

MaFu

Well-Known Member
Licensed User
Longtime User
This is because you would use only 0 and 1. Several programming languages interpretes 0 as false and all other values as true. And i can use this routine also this way, but not with your implementation.
If only 0 and 1 should be allowed then more checks are needed. In this point i agreed with you.
But for a simple check or maybe a more "fuzzy" comparison is the "<> 0" check the right way.
 
Top