Shop OBEX P1 Docs P2 Docs Learn Events
Converting char to bits? — Parallax Forums

Converting char to bits?

bulkheadbulkhead Posts: 405
edited 2006-02-03 01:34 in General Discussion
If I have a char that holds 8 bits (ex, 10001001), how can I create a boolean statement to check if a certain bit (lets say the 5th one) is a 0 or a 1?

Comments

  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2006-01-30 04:28
    Put the following routine in your main class

    static boolean bittest(int index, int value) {
    · return (value&(1<<index)) != 0;
    }

    To test for·bit5 set use
    if (bittest(5,value)) {
    · //code to execute if bit5 is set
    }
    or use
    if (bittest(5,value)==true) {
    }

    To test for bit5 clear use
    if (!bittest(5,value)) {
    · //code to execute if bit5 is clear
    }
    or use
    if (bittest(5,value)==false) {
    }

    Other option is to extract a bit value

    static int bit(int index, int value) {
    · return (value>>>index)&1; //return 0 or 1
    }

    Then use for testing
    if (bit(5,value)==1) {
    }

    if (bit(5,value)==0) {
    }

    regards peter
  • bulkheadbulkhead Posts: 405
    edited 2006-01-30 05:46
    Wow, that's pretty simple. I was going to convert it to a string and go from there, but that does the job much quicker. Thanks!
  • Peter VerkaikPeter Verkaik Posts: 3,956
    edited 2006-01-30 06:53
    You can make it more general, to allow testing for multiple bits

    //bits_mask: set bit to 1 to include bit in test
    //bits_match: set bit to 0 or 1 to match value bits
    //value: the bits to test
    static boolean bitmatch(int bits_mask, int bits_match,·int value) {
    · int result = (value ^ bits_match)&(bits_mask); //result is 0 if bits match
    · return result == 0;
    }
    To test for bit5 set use
    if (bitmatch(0x0020,0x0020,value)) {
    }

    regards peter

    ·
  • Ryan ClarkeRyan Clarke Posts: 738
    edited 2006-02-03 01:34
    The masking approach is much more useful...

    Ryan

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Ryan Clarke
    Parallax Tech Support

    RClarke@Parallax.com
Sign In or Register to comment.