Page 1 of 1

Bits and Bytes

Posted: Sat Mar 05, 2011 6:27 pm
by Simon Knight
I am seeking advice on the best method of reading and writing bit data from bytes. For example I need to read the three most significant bits of a byte but can not see a simple way of reading them in Livecode; in other languages I would use a bit shift command and shift them right by 5 bits. How should I achieve this in Livecode? Should I convert the bytes to stings of binary and use the string handling to extract the values?

Simon

Re: Bits and Bytes

Posted: Sat Mar 05, 2011 6:33 pm
by BvG
You use binarydecode. the position can be handled by yourself, for example by saying:

Code: Select all

put char 5 to 10 of theBinary into toDecode
local tempData
put binarydecode("x5H3",toDecode,tempData) into trash
put tempData

Re: Bits and Bytes

Posted: Sat Mar 05, 2011 7:08 pm
by Simon Knight
Hi (again),
I will play with the binarydecode "function" but given that H2 is the way to read a single byte who knows what x5H3 does?
Simon

Re: Bits and Bytes

Posted: Sat Mar 05, 2011 7:23 pm
by BvG
Obviously it'll represent 1.5 bytes, making it a representation for 12 bits.

Re: Bits and Bytes

Posted: Sat Mar 05, 2011 7:45 pm
by Simon Knight
It looks like it may be unwise to attempt to cross character/byte boundries. I have been experimenting with the following code:

Code: Select all

put byte 1 of theBinarydata into twobytes
put byte 2 of theBinarydata after twobytes

put binarydecode("b*", twoBytes, tTwoBytesBits) into theNumConversions
put CR & "Two bytes as binary " & tTwoBytesBits after fld"debug"

put binarydecode("B8B3", twoBytes, tLeadingBits,tWantedBits) into theNumConversions
put CR & "Extract some data " & tWantedBits after fld"debug"
where the final two lines attempt to extract some bits. The posted code runs but changing the format string to B9B2 results in a silent failure and suggests that the function is character based and a little broken. The function documentation is very poor.

My plan of action is to use the binarydecode and binaryencode functions to convert bytes of data to/from binary strings. I will write my own routines for manipulating the bit characters of these strings.

As to H3. A quick and dirty test with two bytes of data did indeed result in three hex characters. Then I added an x1 before the H3 i.e. "x1H3" wondering if this would select the last 12 bits. The result is that it is a silent failure followed by the dev environment looping forever - not very pretty.

Simon