Shop OBEX P1 Docs P2 Docs Learn Events
Converting Byte into Array of Bits — Parallax Forums

Converting Byte into Array of Bits

pharylonpharylon Posts: 5
edited 2013-07-12 02:52 in General Discussion
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

  • Mike GreenMike Green Posts: 23,101
    edited 2013-07-11 20:12
    Why?

    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 ].
  • lanternfishlanternfish Posts: 366
    edited 2013-07-12 01:51
    Thanks for the useful tip on using the B register. Very handy.
  • LoopyBytelooseLoopyByteloose Posts: 12,537
    edited 2013-07-12 02:52
    This is an interesting question... just because there is really no reason to do so.

    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.
Sign In or Register to comment.