Format in Binary notation


Gammatech

Recommended Posts

Hi,

There doesn't seem to be any inbuilt functions to display an eight bit number in binary format. As far as I can see Format() handles everything except binary.

I tried a for loop to step through the bits using TestBit(value,Index)

For(Private Index = 0, Index < 8, Index ++)
   If(TestBit(Digital1[0],Index) == 1)
	  Insert(BinaryStr,(7-Index),"1")
	Else
	   Insert(BinaryStr,(7-Index),"0")
	EndIf
EndFor

Digital1[0] is the latest value from the channel that I recover from the serial input and this displays as 193 or 129 depending on a switch at the remote end. BinaryStr is declared as a Global String = "********"

The above code does not work as binaryStr stays as "********" all of the time without the second character changing with the switch nor indeed the two set bits namely bit 7 and bit 0 ever showing as ones, none of those bits that are not set cause the insertion of a "0" either. What am I doing wrong and is there any better way to display the value in binary format. A variable value component displays the value of Digital1[0] as 129 or 193 but I would like to show it as 10000001 or 11000001 respectively.

As always - many thanks,

Martin

Link to comment
Share on other sites

You can do it in a single expression like this:

MakeReverse(chra((to.Bit(value))[][0,7] + 48))

where value is the desired byte. to.Bit converts a binary value into an array of 1's and 0's. Its an array with 1 row and 32 columns (it assumes 32 bit). The [][0,7] reduces this down to just the first 8 bits. We then add 48 (ASCII '0') to it, and do chra(), which doesn't care about the array's dimension rows vs cols, and that converts it to a string of 0's and 1's. to.bit returns the values from LSB to MSB, so to display it with MSB first, we do the makeReverse() function which just reverses the characters in a string.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.