View previous topic :: View next topic |
Author |
Message |
scottc
Joined: 16 Aug 2010 Posts: 95
|
Accessing Individual Bits of a 8bit variable |
Posted: Wed Sep 08, 2010 11:32 pm |
|
|
I was wondering does CCS support accessing the indvidual bits of
a variable similar to below
Code: |
if(value1.b1 == value2.b2)
++value3
|
In essence, if bit1 of value1 = Bit2 of value2, I increment value 3.
Another compiler I have does it this way so was curious to know the
simplest method ccs uses. I did not spot anything in the manual that
was obvious.
Thanks Scott. |
|
|
FFT
Joined: 07 Jul 2010 Posts: 92
|
|
Posted: Thu Sep 09, 2010 2:12 am |
|
|
Not at all,
You can test the bits by logical "and/or".
Code: | if(!!value1&(1<<1) == !!value2&(1<<2))
++value3 |
Or CCS has some built-in functions for testing or assigning bits of variables.
An another way is to define a struct or union to access any bit of the variable. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Thu Sep 09, 2010 2:17 am |
|
|
Several different ways.
First, #bit.
Code: |
int8 val,value3;
#bit b1=val.1
#bit b3=val.3
val=x;
if (b1==b3) ++value3;
|
This declares new 'bit' variables, that directly access specified bits in 'val'.
Second, a union.
Code: |
union bits {
int8 whole;
int1 b[8];
} val;
int8 value3;
val.whole=x;
if (val.b[1]==val.b[3]) ++value3;
|
Makes an array of 8 bits, as a 'pseudonym' for the bits in the byte.
Then the 'bit_test' function:
Code: |
int8 val,value3;
val=x;
if (bit_test(val,1)==bit_test(val,3)) ++value3;
|
Obviously then standard masking etc..
Best Wishes |
|
|
scottc
Joined: 16 Aug 2010 Posts: 95
|
|
Posted: Thu Sep 09, 2010 3:25 am |
|
|
Thanks for the help guys, It looks like there are many ways to skin that cat
I banged on the keys for a bit and did it like this
Code: |
if((bit_test(value1,1)) == (bit_test(value2,2)))
|
and that appeared to get accepted by the compiler.
It would be neat I think if the compiler could understand it like
Code: |
if(value1.b1 == value2.b2)
|
To me thats a way easier read. But then again I'm a noob with ccs so
onwards through the fog I go.
Thanks again Scott. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Thu Sep 09, 2010 7:21 am |
|
|
The 'downside' from a C point of view, of the '.' notation, is that it is already used.... Fred.something, in C, says that 'something', is a structure or union element of 'Fred', so using '.' for bits, could be rather confusing, with (as shown in the union example), it not being 'normal' to be able to access the whole byte just using the 'name' without the element...
Best Wishes |
|
|
|