View previous topic :: View next topic |
Author |
Message |
rober0 Guest
|
Bytes and bits... |
Posted: Sun Mar 25, 2007 1:01 am |
|
|
I'm playing with the demo....so you understand i'm learning.
I'm porting to C a Basic program and ..how do you translate this:
FOR x= 7 to 0 step -1
if MYBYTE.0(x) = 1 then ..do something
else
do something else.
ENDIF
With this simple cycle i read ( starting from bit #7) every bit of the variable MYBYTE .
Thanks. Roberto |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1908
|
|
Posted: Sun Mar 25, 2007 1:37 am |
|
|
There's a few different ways to do this, but probably the simplest to understand would be:
Code: | signed int8 x;
int8 MBYTE = .....; // set MBYTE to whatever you wish here
for (x = 7; x > 0; x--) {
if (bit_test(MBYTE, x)) {
// do something if that particular bit is a '1'
}
else {
// do something else if that bit is a '0'
}
} |
It's important that x be declared as a signed int8 otherwise the test in the for loop (is x greater than 0?) will always be true and the loop will never exit. Actually now that I think about it you could get around this with this slight modification to the code above:
Code: | int8 x; // note difference here
int8 MBYTE = .....; // set MBYTE to whatever you wish here
for (x = 0; x < 8; x++) { // note difference here
if (bit_test(MBYTE, 7 - x)) { // note difference here
// do something if that particular bit is a '1'
}
else {
// do something else if that bit is a '0'
}
} |
|
|
|
Guest
|
|
Posted: Sun Mar 25, 2007 2:39 am |
|
|
Wow.. thanks for your prompt reply.
Code: |
signed int8 x;
int8 MBYTE = .....; // set MBYTE to whatever you wish here
for (x = 7; x > 0; x--) {
if (bit_test(MBYTE, x)) {
// do something if that particular bit is a '1'
}
else {
// do something else if that bit is a '0'
}
}
|
This will surely work but, as i need to read all the 8 bits of MBYTE, loop should be
(x=7; x=0; x--). x is greater or equal than 0.
Thanks again.....now i will face the interrupt matter :-))
Roberto |
|
|
newguy
Joined: 24 Jun 2004 Posts: 1908
|
|
Posted: Sun Mar 25, 2007 1:37 pm |
|
|
D'oh! Good catch with my mistake. That for loop should read as follows:
Code: | signed int8 x;
int8 MBYTE = .....; // set MBYTE to whatever you wish here
for (x = 7; x >= 0; x--) { // test is now fixed
if (bit_test(MBYTE, x)) {
// do something if that particular bit is a '1'
}
else {
// do something else if that bit is a '0'
}
} |
|
|
|
kevcon
Joined: 21 Feb 2007 Posts: 142 Location: Michigan, USA
|
|
Posted: Mon Mar 26, 2007 12:40 pm |
|
|
You can do it with a DO WHILE loop too.
Code: |
unsigned int8 i = 7;
unsigned int8 MYBYTE;
do {
if ( bit_test( MYBYTE, i ) ) {
//Bit is one
}
else {
//Bit is zero
}
} while( --i != 255 );
|
|
|
|
|