Search code examples
phpmathvb6byte

Translating VB6 Code to PHP - byte as parameter?


Im working on a little project an i need to convert some vb6 code to php. I'm at a stand still because I'm not sure how I'm supposed to be convert this set of code into PHP or even if it's possible.

This is the vb6 code

Private Function Ist_Bit_Gesetzt_Integer(ByVal arg As Integer, _
                                         ByVal bitpos As Byte) As Boolean
   
  If bitpos > 16 Or bitpos < 1 Then Exit Function
     
  If bitpos = 16 Then
    Ist_Bit_Gesetzt_Integer = arg < 0
  Else
    Ist_Bit_Gesetzt_Integer = arg And (2 ^ (bitpos - 1))
  End If
  
End Function

And this is my translated code

function Ist_Bit_Gesetzt($arg, $pos)
{
    if($pos > 16 || $pos < 1) 
        return false;

    if($pos == 16)
    {
        return (bool)($arg < 0);
    }else{
        return (bool)($arg && (pow(2 , ($pos - 1))));
    }
}

The problem is, it doesnt work as expected, and i think it's because in vb6 the parameter bitpos is declared as Byte. And to be honest i also don't understand the calculation arg And (2 ^ (bitpos - 1))


Solution

  • The function name translates to "Is Bit Set?", the purpose is to tell if the bit in the $pos position of $arg is set.

    pos(2, ($pos - 1)) is equivalent to 1 << ($pos - 1), it creates a number with a 1 bit in position $pos (counting from the right, starting from 1). This will then be used as a bit mask to combine with $arg; all its bits will be cleared except for the one corresponding to the 1 bit in this result.

    You need to use the & operator to perform this bitwise masking. && is a logical operation.

    Converting this result to bool returns true if the number is non-zero (which will happen when the bit is set), false if it's zero (when the bit is not set).

    So change the last line to:

            return (bool)($arg & (1 << ($pos - 1)));