# Turning two bits into one two-bit binary number

Status
Not open for further replies.

#### BiscuitDuke

##### Newbie level 6 Hello everyone. I need help on a homework assignment:

Write a C program that treats A1A0, A3A2, and A5A4 as three 2-bit unsigned binary
number. The program should output the sum of those three numbers onto B.

I need help with the 'treat A1A0... 2-bit unsigned binary number.' I figure I'd have to use the GetBit function but i dont know how to get two bits and make them a one two-bit number.

#### horace1 I assume you are reading the bits of PORTA
you can extract the bits so
Code:
int A10=PORTA & 3;
int A32 = (PORTA >> 2) & 3
etc
is that what you want to do?

#### horace1 if A1 and A0 are one bit variables to create a two bit variable you shift A1 one biit left and add A0 to it
Code:
A1A0=(A1<<1) + A0;

#### Micro_Tech90

##### Newbie level 1 what if id want to set B to the reverse of A, such at B7 = A0, B6 = A1; while using a for loop. This is using the same program as above. Any help is appreciated.

#### Aussie Susan If 'A' and 'B' are arrays (i.e. "B7" really means "B" in c-like syntax) then you can use an index into the arrays within the for-loop.
If they are separate variables, but you can define them in a structure (which gives you come control over their relative addresses) then create a pointer to the start or end of the structures and increment/decrement the pointers within the for-loop.
Susan

#### betwixt

##### Super Moderator
Staff member Looking at the simulator it appears 'A' is an 8-bit input port and 'B' is an 8-bit output port in a hypothetical processor. The question is one of adding the 'A' bit pairs together and puting the result on 'B' so it boils down to shifting them to align with the LSB, adding them to a variable (it doesn't say whether 'B' can be used as an accumulator) then outputting the result on 'B'.

BiscuitDuke - it's your work but try this workflow:
C = A & 0b00000011;
C += (A & 0b00001100) >> 2;
C += (A & 0b00110000) >> 4;
B = C;

I show the numbers in binary so you can see how the '&' operator can be used to isolate the '11' bits from the rest of the value in 'A' so only the ones you are interested remain and the other bits are set to zero.

The '+=' is short hand for "the value on the right is added to the value on the left"

The '>>' operator shifts the whole 'A' value by the number of places in the number. In my example you can see it is used to move the bit pairs to the rightmost (LSB) places so all three pairs are aligned with each other before adding them.

Brian.

#### Aussie Susan 