The simFlight Network Forums

# Question to read a Bit via LUA

## Recommended Posts

Hello,

i hope anyone can help.

I am a starter in LUA, but i have to read a Bit out of a 2 Byte Offset.

The Offset is 0x04F0 and i want to read Bit number 14 and 6.

I tried

for Bit 0 and it works, but how can i read Bit number 14 and 6 ?

Pls, can anyone help her?

Thanks

Matthias

##### Share on other sites

I am a starter in LUA, but i have to read a Bit out of a 2 Byte Offset.

The Offset is 0x04F0 and i want to read Bit number 14 and 6.

I tried

for Bit 0 and it works, but how can i read Bit number 14 and 6 ?

First of all, "readUB" is "read unsigned byte", and a byte only contains 8 bits (numbered 0-7). So you'll never get to bit 14. I think you'll find that Project Magenta's offset 04F0 is a 16-bit Word, so you need to read it with ipc.readUW.

Second, to isolate and therefore test individual bits in a binary value you need to use the logical function "And". For your bit 0 you'd do

if logic.And(psCMD1, 1) ~= 0 then

...

end

because bit 0 is 2^0 = 1.

To isolate and test other bits you need the mask value (the 1 in the above And function). You could use hexadecimal values which makes it easier to visualise:

0x0001 for bit 0

0x0002 for bit 1

...

0x8000 for bit 15

Regards

Pete

##### Share on other sites

Hello Pete,

thanks a very lot for explaining me this!!

Matthias

##### Share on other sites

• 6 years later...

Hello,

i am sorry, but i dont understand the "mask".

If 0x0001 is for bit 0 and 0x0002 is for bit 1, so must be

0x0001 for bit 0
0x0002 for bit 1
0x0004 for bit 2
0x0008 for bit 3
0x0016 for bit 4
0x0032 for bit 5
0x0064 for bit 6
0x0128 for bit 7

is correct or not? Because you hve written 0x8000 is bot bit 15, what i can not understand??

Matthias

##### Share on other sites

1 hour ago, mroschk said:

If 0x0001 is for bit 0 and 0x0002 is for bit 1, so must be

0x0001 for bit 0
0x0002 for bit 1
0x0004 for bit 2
0x0008 for bit 3
0x0016 for bit 4
0x0032 for bit 5
0x0064 for bit 6
0x0128 for bit 7

No. the 0x in front signifies hexadecimal, not decimal. i.e. base 16 not 10 (just as binary is base 2). Each digit goes from 0 to F (0-9 then A, B, C, D, E, F), with F = 15.

So 0x0010 = 16 in decimal, 0x0100 = 256 and so on. ox8000 = 32768.

Your list would be correct without the 0x (i.e. decimal), but masks are much easier to understand in hexadecimal. For example 0x005A = binary 0000 0000 0101 1010, or bits 1,3,4 and 6. Testing for those bits in decimal would be a mask value of 90, much more difficult to see exactly the bits being tested.

Pete

## Create an account

Register a new account