Search code examples
.netfunctionxor

General: Best function name for returning AND values


I want to design a function that returns values that can be AND / ORed.

My attempt is:

Public Function getCompatibleValue(ByVal uIndex As Integer) As Integer

    Dim i As Integer = 0

    If uIndex = 0 Then
        i = 0
    ElseIf uIndex = 1 Then
        i = 1
    ElseIf uIndex = 2 Then
        i = 2
    ElseIf uIndex = 3 Then
        i = 4
    ElseIf uIndex = 4 Then
        i = 8
    ElseIf uIndex = 5 Then
        i = 16
    ElseIf uIndex = 6 Then
        i = 32
    ElseIf uIndex = 7 Then
        i = 64
    ElseIf uIndex = 8 Then
        i = 128
    End If

    Return i

End Function

But I am neither sure that the name "getCompatibleValue" is good nor that my function logic is very efficient.

Perhaps somebody could share his thoughts on this.

Thank you very much!


Solution

  • There is no reason to have a function in the first place. You can do this directly with the exponentiation operator:

    i = If (uIndex = 0, 0, 2 ^ (uIndex - 1))
    

    This will give you the value as a Double, but you can then cast it to Integer.