Converting Byte into Array of Bits
pharylon
Posts: 5
The title pretty much says it all. I want to turn (say) 9 into 1001. There's got to be an easy way with bitshifting, right?
Comments
If you're wanting to display a number as binary using a Stamp, the BIN formatters are much easier to use. See the Manual, particularly Appendix C. If you want to access the bits you can use .BIT0 and a subscript to access the bits directly in PBasic. Look at the section of the Manual on memory storage for details.
If you want to access bits in Spin, the easiest way is to use one of the otherwise unused B registers like DIRB or OUTB, copy the value into say OUTB, then reference the bits like OUTB[ 0 ].
At the level of machine code, there are a set of very useful instructions that can reach or manipulate individual bits to anything you want.
We have AND, OR, XOR, NOT that can combine with a second byte to filer in a variety of ways depending in part of whether you want to find 0s or 1s.
And then, if position is important with have left shift, a left rotate, a right shift and a right rotate.
Arrays are groups of bytes in RAM or other memory. To take one byte and distribute each bit into an array would waste space as it would take 8 bytes. And then to reached in item in the array would take more work from the CPU.
So it is all rather wasteful, but possible to do.
Of course PBasic provides a good solution, but it is also interesting to consider what any microcontroller might actually do.
Are you asking how binary is normally converted ASCII numbers for display? That is usually done with converting binary to a decimal representation (4 bits for each digit) and then adding the 4bit value to a constant that will display numbers correctly in ASCII.
And with a 7-segment display, the 4 bit value would locate a matching value in a lookup table to output the right highs and lows to the display's LEDs.