Reputation: 193
I have two characters
char c1='A', c2 = 'B';
since 8-bit binary of A
is 01000001
and binary of B
is 01000010
. I want the left-most bit of B
to be put into the right-Most bit of A
so that c1 becomes 01000000
. I am doing this by calculating binaries A and B and then geting new binary and then doing described process and then assigning the new binary to c1
.
My question is whether there is there any efficient way to do this?
Upvotes: 0
Views: 175
Reputation: 781706
The leftmost bit of c2
is:
c2 & 0x80
To move this into the rightmost bit, you use a right-shift:
(c2 & 0x80) >> 7
To combine this with c1
, you first have to clear out the rightmost bit of c1
:
(c1 & 0xfe)
Then you combine them with |
:
c1 = (c1 & 0xfe) | ((c2 & 0x80) >> 7);
You should also change your declarations to unsigned char
to avoid problems with the sign bit. It's generally best to use only unsigned
variables when using bitwise operations.
Upvotes: 3