B4J Question Get value out from bit 0 to 2 (3 bits in a byte)

DonManfred

Expert
Licensed User
Longtime User
Hello,

i stuck on how to interpret some byte values i got from a game.

In this case i read data from a bytearray

B4X:
    Dim b As Byte = raf.ReadunsignedByte(10)
Log("RaceStateFlags:"&NumberFormat2(Bit.ToBinaryString(Bit.And(0xff, b)), 8, 0, 0, False)&" -> "&b)

From my research i found information on a simular app written in C.

B4X:
// mTelemetryData.sGameSessionState=((u8)pMemory->mGameState)|(((u8)pMemory->mSessionState)<<4); // (enum 3 bits/enum 3 bits)->u8
#define UNPACK_TELEMETRY_GAMESTATE(ptr)              UNPACK_UNSIGNED((ptr)->sGameSessionState, 3, 0)
#define UNPACK_TELEMETRY_SESSIONSTATE(ptr)           UNPACK_UNSIGNED((ptr)->sGameSessionState, 3, 4)

So i guess i need to do the same with the values...

In this example i would like to split the byte into its two values. Here the values of
UNPACK_UNSIGNED((ptr)->sGameSessionState, 3, 0)
and
UNPACK_UNSIGNED((ptr)->sGameSessionState, 3, 4)

How could i do this in b4j?
 

Daestrum

Expert
Licensed User
Longtime User
B4X:
Dim inline as JavaObject
....
    inline=Me
    Dim value As Int = 23
    '    params =  Value,bit start, bit end (inclusive)
    Log(inline.RunMethod("getBits",Array(value,0,2)))
    Log(inline.RunMethod("getBits",Array(value,3,5)))
....
#if java
public static byte getBits(int v,int st,int end){
    byte res = 0;
    for(int a=st;a<=end;a++){
        res += (byte)(1<<a);
    }
    return (byte)((res & v)>>st);
}
#end if
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
If you wanted in pure B4J code
B4X:
...
    Log(getBits(value,0,2))
    Log(getBits(value,4,6))
...
Sub getBits(v As Int,bitStart As Int,bitEnd As Int) As Int
    Dim res As Int = 0
    For a = bitStart To bitEnd
        res = res + Power(2,a)      
    Next
    Return (Bit.ShiftRight(Bit.And(v,res),bitStart))
End Sub
 
Upvote 0
Top