|
|
View previous topic :: View next topic |
Author |
Message |
hayee
Joined: 05 Sep 2007 Posts: 252
|
how to convert bits into bytes |
Posted: Mon Jul 07, 2008 5:08 am |
|
|
Hi Everyone,
I have 8 bits like
Code: | a=input(PIN_A0);
b=input(PIN_A1);
c=input(PIN_A2);
d=input(PIN_A3);
e=input(PIN_B0);
f=input(PIN_B1);
g=input(PIN_B2);
h=input(PIN_B3); |
Now I want to combine those bits and make 1 byte. How would I do that?
I am using ccs compiler version 4.020.
Thanks. |
|
|
Ttelmah Guest
|
|
Posted: Mon Jul 07, 2008 6:17 am |
|
|
First, why not do it much simpler, and read the two lots of four bits already together?. If you read these nibbles, then you only need to multiply one by 16 (or shift it four places), and add them together.
To do it 'bit by bit', is rather more work, but there are literally dozens of ways of doing this.
First, you could just use the shift_left (or right, depending on the order you want the bits) instruction, and shift the bits in. So:
Code: |
int8 val=0;
shift_left(&val,1,a);
shift_left(&val,1,b);
shift_left(&val,1,c);
//etc.
|
would put all the bits into the 'val' byte.
Second, just multiply the bits by 2,4,8 etc., so:
Code: |
val=a*128 + b*64 + c*32 + d*16 + e*8 + f*4 + g*2 h
|
The compiler will do this by shifting the bits, rather than perfroming an actual multiplication, so the result is very similar.
Third, you could use the 'bit_set' function, just testing each value, and applying this if necessary.
There are loads more variants on this...
Doing it on the two nibbles, is vastly quicker, and easier. So:
Code: |
int8 anibble,bnibble,val;
anibble=input_a() & 0xF;
bnibble=input_b() & 0xF;
val=anibble*16 + bnibble;
|
Best Wishes |
|
|
hayee
Joined: 05 Sep 2007 Posts: 252
|
|
Posted: Mon Jul 07, 2008 6:28 am |
|
|
Thanx Ttelmah.
u did a great job |
|
|
hayee
Joined: 05 Sep 2007 Posts: 252
|
|
Posted: Mon Jul 07, 2008 6:32 am |
|
|
One more question.
can i see these nibble or bytes on my pc using serial port.i mean by using printf command.if yes how? |
|
|
Ttelmah Guest
|
|
Posted: Mon Jul 07, 2008 8:04 am |
|
|
Of course you can print them.
Depends how you want to display the result.
So:
printf("%u/n/r",val);
will just output the numeric value of the pattern, as a decimal number.
printf("%2x/n/r",val);
will print two hexadecimal digits, representing the nibbles being seen.
Best Wishes |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|