Binary operation in C -
i have 2 characters
char c1='a', c2 = 'b';
since 8-bit binary of a
01000001
, binary of b
01000010
. want left-most bit of b
set right-most bit of a
c1 becomes 01000000
. doing calculating binaries , b , geting new binary , doing described process , assigning new binary c1
. question whether there there efficient way this?
the leftmost bit of c2
is:
c2 & 0x80
to move rightmost bit, utilize right-shift:
(c2 & 0x80) >> 7
to combine c1
, first have clear out rightmost bit of c1
:
(c1 & 0xfe)
then combine them |
:
c1 = (c1 & 0xfe) | ((c2 & 0x80) >> 7);
you should alter declarations unsigned char
avoid problems sign bit. it's best utilize unsigned
variables when using bitwise operations.
c binary char
No comments:
Post a Comment