View previous topic :: View next topic |
Author |
Message |
Geps
Joined: 05 Jul 2010 Posts: 129
|
Convert Int8 To Short Array? |
Posted: Thu Dec 09, 2010 5:35 am |
|
|
Hi,
I have a function:
Code: | void function_one(int8 Byte1, int8 Byte2, int8 Byte3, int8 Byte4){
//calculations on Bytes
//calculate Byte parity bits
}
|
What's the cleanest way to access the individual bits of the bytes for my parity bit calculation?
Is it possible to swap between int8 and 8 element short array? Surely they're exactly the same in terms of memory allocation on the pic?
Cheers, |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19510
|
|
Posted: Thu Dec 09, 2010 5:54 am |
|
|
Yes.
This is what a union allows you to do.
So (for example):
Code: |
union {
int1 bits[8];
int8 whole;
} splitter;
void main(){
int8 ctr,nobits=0;
splitter.whole=0xAA;
for (ctr=0;ctr<8;ctr++) {
if (splitter.bits[ctr]) nobits++;
}
//Here 'nobits' has the number of bits that are non zero in the byte
while(1);
}
|
However, caveat, it takes quite a bit of work to actually calculate a bit reference from the array index. It will be _quicker_ to simply declare a byte called 'mask', and do something like:
Code: |
void main(){
int8 ctr,mask=1,val;
val=0xAA;
for (ctr=0;ctr<8;ctr++) {
if (val & mask) nobits++;
val<=1;
}
while(1);
}
|
Here each loop, only has to rotate the mask one bit, while in the original code, the compiler has to start with a mask, and rotate it 'ctr' bits each time...
YPYMATYC.
Best Wishes |
|
|
Geps
Joined: 05 Jul 2010 Posts: 129
|
|
Posted: Thu Dec 09, 2010 7:19 am |
|
|
Thanks Ttelmah,
I was having a think about it and came up with this way. Any feedback appreciated.
Reference a pointer to the byte
Recast the pointer to short type
Dereference and store the value as the byte's MSB
Increment pointer
Deference again for the MSB-1
Repeat all the way along the byte. |
|
|
collink
Joined: 08 Jan 2010 Posts: 137 Location: Michigan
|
|
Posted: Thu Dec 09, 2010 7:52 am |
|
|
No, do it how Ttelmah showed you. I'm almost positive that the CCS compiles does NOT support bit level pointers. Even if it did it would be a nasty way to do it. The bit masking approach is clean and readable.
Geps wrote: | Thanks Ttelmah,
I was having a think about it and came up with this way. Any feedback appreciated.
Reference a pointer to the byte
Recast the pointer to short type
Dereference and store the value as the byte's MSB
Increment pointer
Deference again for the MSB-1
Repeat all the way along the byte. |
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19510
|
|
Posted: Thu Dec 09, 2010 9:30 am |
|
|
Collink is right. Think about it for a moment, a 'pointer', is a memory address. How can you have such an address for a bit?....
Do a search for 'short' on the manual. Only about a dozen hits. About 3/4 the way down, this is explicitly stated.
You spoke about the 'cleanest' way. Even if possible, this would be 'filthy'.....
Best Wishes |
|
|
|