Help with bit operations, please

junglejet

Active Member
Licensed User
Longtime User
I am struggling with bit shift, and and or operations.
What I need are unsigned bytes and integers, but these are not avail.
Yes, I have finally discovered that there is an bit.unsignedshiftright and that bit.and(b,0xFF) does an integer cast without the leftmost bit set.

So far so good. But I am still struggling to get a few operations translated from Delphi to B4A.
Already I have put a single operation into one line, to rule out any problems with casted expressions, but still the results are partially wrong. It seems some sort of signed integer conversion is still taking place under certain conditions.

Any help is very much appreciated.
Thanks in advance
Andy

The caller sub:
B4X:
Sub parse (b() As Byte, f As TFf) As TFf
         Dim i,j As Int
'This is the Delphi code - char numbering in string is correct as shown
'decode((ord(st[2]) AND $1F) shl 8 + ord(st[3]),13,f);
         i=Bit.And(b(2),0xFF) 
         i=Bit.And(i,0x001F) 'ord(st[2]) AND $1F
         i=Bit.ShiftLeft(i,8) 'shl 8

         j=Bit.And(b(3),0xff) 
         i=Bit.Or(i,j)
         i=Bit.And(i,0x1FFF) 'for whatever
         f=decode(i,13,f)
         Return f
End Sub

Part of the called sub:

B4X:
Sub decode(w As Int, bits As Int, f As TFf) As TFf
   Dim a,b,c,d As Int
   If bits=13 Then
      If Bit.And(w,0x0010)=0 Then 'is always 0
      Else
' Delphi code
' i:= ( (w AND $000f) OR ((w AND $0020) shr 1) OR ((w AND $1F80) shr 2) ) * 25 - 1000;
         a=Bit.And(w,0x000F)
         b=Bit.And(w,0x0020)
         
         b=Bit.unsignedShiftRight(b,1)
         a=Bit.Or(a,b)
         
         b=Bit.And(w,0x1F80)
         b=Bit.unsignedShiftRight(b,2)
         a=Bit.Or(a,b)
         a=Bit.And(a,0x07ff) 'for whatever
         f.alt=a*25-1000
      End If
      Return f
    End If
End Sub
 

mc73

Well-Known Member
Licensed User
Longtime User
Note sure but in your Delphi code, I see addition, while in your b4 code, the logical 'or'.
You write:
B4X:
ord(st[2]) AND $1F) shl 8 + ord(st[3]
and then
B4X:
i=Bit.Or(i,j)
. Just my notice, don't know if this is causing the different results.
 
Last edited:
Upvote 0

junglejet

Active Member
Licensed User
Longtime User
Seems logical, but I found that this does not work:

B4X:
Dim df as byte
df = Bit.And(b(0),0xff)
df = Bit.unsignedShiftRight(df,3)

df remains signed.

The work around is
B4X:
Dim df as int
df = Bit.And(b(0),0xff)
df = Bit.unsignedShiftRight(df,3)
 
Upvote 0
Top