Converting char to bits?
bulkhead
Posts: 405
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
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
//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
▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Ryan Clarke
Parallax Tech Support
RClarke@Parallax.com