Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
BitwiseDataManipulation
BitwiseoperationsMoreonintegers
bitwise operatorsBitwiseoperatorsonfixed-width bitvectors.
AND&OR| XOR^ NOT~
LawsofBooleanalgebraapplybitwise.e.g.,DeMorgan’s Law:~(A|B)=~A&~B
01101001&0101010101000001
01101001|01010101
01101001^01010101 ~01010101
01010101^01010101
2
ex
Aside:setsas bitvectorsRepresentation:n-bitvectorgivessubsetof{0,…,n–1}.
ai =1 ≡i Î A
01101001 {0,3,5,6}76543210
01010101 {0,2,4,6}76543210
BitwiseOperations SetOperations?& 01000001 {0,6} Intersection| 01111101 {0,2,3,4,5,6} Union^ 00111100 {2,3,4,5} Symmetricdifference~ 10101010 {1,3,5,7} Complement
3
ex
bitwise operatorsinC& | ^ ~ applytoanyintegral datatype
long,int,short,char, unsigned
Examples(char)~0x41 =
~0x00 =
0x69 & 0x55 =
0x69 | 0x55 =
Manybit-twiddlingpuzzlesinupcomingassignment
4
ex
logical operationsinC&&||! applytoany"integral"datatype
long,int,short,char, unsigned
0is false nonzerois true resultalways 0or1
earlytermination a.k.a.short-circuitevaluation
Examples(char)!0x41 =!0x00 =!!0x41 =
0x69 && 0x55 =0x69 || 0x55 =
5
ex
Encodeplayingcards.52cardsin4suits
Howdoweencodesuits,facecards?
Whatoperationsshouldbeeasytoimplement?GetandcomparerankGetandcomparesuit
6
Twopossiblerepresentations
52cards– 52bitswithbitcorrespondingtocardsetto1
“One-hot”encodingHardtocomparevaluesandsuitsindependentlyNotspaceefficient
4bitsforsuit,13bitsforcardvalue– 17bitswithtwosetto1
Pairofone-hotencodedvaluesEasiertocomparesuitsandvaluesindependentlySmaller,butstillnotspaceefficient
7
52bitsin2x32-bitwords
TwobetterrepresentationsBinaryencodingofall52cards– only6bitsneeded
Numbercardsuniquelyfrom0Smallerthanone-hotencodings.Hardtocomparevalueandsuit
Binaryencodingofsuit(2bits)andvalue(4bits)separately
NumbereachsuituniquelyNumbereachvalueuniquelyStillsmallEasysuit,valuecomparisons
8
low-order6bitsofabyte
suit value
mask: abitvectorthat,whenbitwiseANDed withanotherbitvectorv,turnsallbut thebitsofinterestinv to0
CompareCardSuits
char hand[5]; // represents a 5-card handchar card1, card2; // two cards to compare...if ( sameSuit(hand[0], hand[1]) ) { ... }
9
#define SUIT_MASK 0x30
int sameSuit(char card1, char card2) {return !((card1 & SUIT_MASK) ^ (card2 & SUIT_MASK));
//same as (card1 & SUIT_MASK) == (card2 & SUIT_MASK);}
0 0 1 1 0 0 0 0
suit value
mask: abitvectorthat,whenbitwiseANDed withanotherbitvectorv,turnsallbut thebitsofinterestinv to0
CompareCardValues
#define VALUE_MASK
int greaterValue(char card1, char card2) {
}
char hand[5]; // represents a 5-card handchar card1, card2; // two cards to compare...if ( greaterValue(hand[0], hand[1]) ) { ... }
10
suit value
ex
Bitshifting
11
10011001
x<<2 1001100100fillwithzeroesonright
x
logicalshiftleft2
00 10011001losebitsonright
10011001
x>>2
x
losebitsonleft
logical shiftright2
11 1 0011001arithmetic shiftright2
fillwithzeroesonleft
fillwithcopiesofMSBonleftx>>2
unsignedshiftingand arithmetic
12
00011011y=x<<2;
0 001101100
x=27;
y==108
11101101y=x>>2;
00 11101101
x=237;
y==59
unsigned
x*2n mod2w
x/2n
unsigned
logicalshiftleft
logicalshiftright
f()
two'scomplementshiftingand arithmetic
13
arithmeticshiftright
11101101y=x>>2;
11 11101101
x=-19;
y==-5
signed
⎣x/2n⎦
10011011y=x<<2;
1001101100
x=-101;
y==108
logicalshiftleft
x*2n mod2wsigned
shift-and-addAvailableoperations
x << k implementsx * 2k
x + y
Implement y = x * 24 usingonly<<,+,andintegerliterals
14
ex
ShiftgotchasLogicalorarithmeticshiftright:howdowetell?C:compilerchooses
Usuallybasedontype:raincheck!
Java: >>isarithmetic,>>>islogical
Shiftann-bittypebyatleast0andnomorethann-1.C:othershiftdistancesareundefined.
anything couldhappen
Java:shiftdistanceisusedmodulonumberofbitsinshiftedtypeGivenint x:x<<34==x<<2
!!!
ShiftandMask: extractabitfieldWriteCcode:extract2nd mostsignificantbyte froma32-bitinteger.
givenshouldreturn:
16
01100001011000100110001101100100x =
00000000000000000000000001100010
Desiredbitsinleastsignificantbyte.Allotherbitsarezero.
ex
Whatdoesthisfunctioncompute?unsigned puzzle(unsigned x, unsigned y) {
unsigned result = 0;
for (unsigned i = 0; i < 32; i++){
if (y & (1 << i)) {
result = result + (x << i);
}
}
return result;
}
17
ex
multiplication
18
00000001
0011
11111110
1100
10111010
1000 01110110
0100
0010
01011001
1101
0+ 1
+ 2
+ 3
+ 4
+ 5
+ 6+ 7– 8
– 7
– 6
– 5
– 4
– 3
– 2– 12
x36
0010x0011
00000100
-2x2-4
1110x0010
11111100
ModularArithmetic
multiplication
19
00000001
0011
11111110
1100
10111010
1000 01110110
0100
0010
01011001
1101
0+ 1
+ 2
+ 3
+ 4
+ 5
+ 6+ 7– 8
– 7
– 6
– 5
– 4
– 3
– 2– 15
x420
0101x0100
00010100
-3x7-21
1101x0111
11101011
4
ModularArithmetic-2
multiplication
20
00000001
0011
11111110
1100
10111010
1000 01110110
0100
0010
01011001
1101
0+ 1
+ 2
+ 3
+ 4
+ 5
+ 6+ 7– 8
– 7
– 6
– 5
– 4
– 3
– 2– 15
x525
0101x0101
00011001
-2x6-12
1110x0110
11110100
-7
ModularArithmetic4
Convert/castsignednumbertolarger type.
21
11111100 8-bit-4
16-bit-4________11111100
00000010 8-bit2
16-bit2________00000010
Rule/name?
CastingIntegersinCNumberliterals:37 issigned,37U isunsigned
IntegerCasting:bitsunchanged,justreinterpreted.Explicitcasting:
int tx = (int) 73U; // still 73unsigned uy = (unsigned) -4; // big positive #
Implicitcasting: Actuallydoestx = ux; // tx = (int)ux;uy = ty; // uy = (unsigned)ty;void foo(int z) { ... }foo(ux); // foo((int)ux);if (tx < ux) ... // if ((unsigned)tx < ux) ...
23
!!!
MoreImplicitCastinginCIfyoumixunsignedand signed inasingleexpression,thensignedvaluesareimplicitlycasttounsigned.
Argument1 Op Argument2 Type Result0 == 0U unsigned 1-1 < 0 signed 1-1 < 0U unsigned 02147483647 < -2147483648 2147483647U < -2147483648-1 < -2 (unsigned)-1 < -2 2147483647 < 2147483648U 2147483647 < (int)2147483648U
Note: Tmin =-2,147,483,648Tmax =2,147,483,64724
!!!Howaretheargument
bitsinterpreted?