BitwiseDataManipulation
Bitwiseoperations
Moreonintegers
bitwise operators
ex
Bitwiseoperatorsonfixed-width bitvectors.
AND&OR| XOR^ NOT~
01101001
&01010101
01000001
01101001
|01010101
01101001
^01010101
~01010101
01010101
^01010101
LawsofBooleanalgebraapplybitwise.
e.g.,DeMorgan’s Law:~(A|B)=~A&~B
2
Aside:setsas bitvectors
ex
Representation:n-bitvectorgivessubsetof{0,…,n–1}.
ai =1 ≡i Î A
01101001
76543210
{0,3,5,6}
01010101
76543210
{0,2,4,6}
BitwiseOperations
&
|
^
~
01000001
01111101
00111100
10101010
{0,6}
{0,2,3,4,5,6}
{2,3,4,5}
{1,3,5,7}
SetOperations?
Intersection
Union
Symmetricdifference
Complement
3
bitwise operatorsinC
& | ^ ~
ex
applytoanyintegral datatype
long,int,short,char, unsigned
Examples(char)
~0x41 =
~0x00 =
0x69 & 0x55 =
0x69 | 0x55 =
Manybit-twiddlingpuzzlesinupcomingassignment
4
logical operationsinC
&&||!
ex
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
Encodeplayingcards.
52cardsin4suits
Howdoweencodesuits,facecards?
Whatoperationsshouldbeeasytoimplement?
Getandcomparerank
Getandcomparesuit
6
Twopossiblerepresentations
52cards– 52bitswithbitcorrespondingtocardsetto1
52bitsin2x32-bitwords
“One-hot”encoding
Hardtocomparevaluesandsuitsindependently
Notspaceefficient
4bitsforsuit,13bitsforcardvalue– 17bitswithtwosetto1
Pairofone-hotencodedvalues
Easiertocomparesuitsandvaluesindependently
Smaller,butstillnotspaceefficient
7
Twobetterrepresentations
Binaryencodingofall52cards– only6bitsneeded
Numbercardsuniquelyfrom0
Smallerthanone-hotencodings.
Hardtocomparevalueandsuit
low-order6bitsofabyte
Binaryencodingofsuit(2bits)andvalue(4bits)separately
Numbereachsuituniquely
Numbereachvalueuniquely
Stillsmall
Easysuit,valuecomparisons
suit
value
8
CompareCardSuits
mask: abitvectorthat,whenbitwise
ANDed withanotherbitvectorv,turns
allbut thebitsofinterestinv to0
#define SUIT_MASK 0x30
0 0 1 1 0 0 0 0
suit
value
int sameSuit(char card1, char card2) {
return !((card1 & SUIT_MASK) ^ (card2 & SUIT_MASK));
//same as (card1 & SUIT_MASK) == (card2 & SUIT_MASK);
}
char hand[5];
// represents a 5-card hand
char card1, card2; // two cards to compare
...
if ( sameSuit(hand[0], hand[1]) ) { ... }
9
ex
CompareCardValues
mask: abitvectorthat,whenbitwise
ANDed withanotherbitvectorv,turns
allbut thebitsofinterestinv to0
#define VALUE_MASK
suit
value
int greaterValue(char card1, char card2) {
}
char hand[5];
// represents a 5-card hand
char card1, card2; // two cards to compare
...
if ( greaterValue(hand[0], hand[1]) ) { ... }
10
Bitshifting
10011001
x
x<<2
1001100100 logicalshiftleft2
losebitsonleft
fillwithzeroesonright
10011001
x
fillwithzeroesonleft
logical shiftright2 00 10011001 x>>2
losebitsonright
arithmetic shiftright2 11 1 0011001 x>>2
fillwithcopiesofMSBonleft
11
unsignedshiftingand arithmetic
unsigned
x=27;
00011011
y=x<<2;
y==108
x*2n mod2w
logicalshiftleft
0 001101100
x/2n
logicalshiftright
11101101
unsigned
x=237;
y=x>>2;
00 11101101
y==59
12
two'scomplementshiftingand arithmetic
signed
10011011
x=-101;
y=x<<2;
y==108
⎣
x/2n
f()
x*2n mod2w
logicalshiftleft
1001101100
⎦
arithmeticshiftright
11101101
signed
x=-19;
y=x>>2;
11 11101101
y==-5
13
ex
shift-and-add
Availableoperations
x << k
x + y
implementsx * 2k
Implement y = x * 24 usingonly<<,+,andintegerliterals
14
Shiftgotchas
!!!
Logicalorarithmeticshiftright:howdowetell?
C:compilerchooses
Usuallybasedontype:raincheck!
Java: >>isarithmetic,>>>islogical
Shiftann-bittypebyatleast0andnomorethann-1.
C:othershiftdistancesareundefined.
anything couldhappen
Java:shiftdistanceisusedmodulonumberofbitsinshiftedtype
Givenint x:x<<34==x<<2
ShiftandMask: extractabitfield
ex
WriteCcode:
extract2nd mostsignificantbyte froma32-bitinteger.
x =
given
shouldreturn:
01100001011000100110001101100100
00000000000000000000000001100010
Allotherbitsarezero.
Desiredbitsinleastsignificantbyte.
16
Whatdoesthisfunctioncompute?
ex
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
multiplication
2
x3
6
-2
x2
-4
0010
x0011
00000100
1110
x0010
11111100
–1
–2
1111
1110
–3
–4
0
+1
0000
0001
1101
+2
0010
+3
1100
0011
– 5 1011
1010
–6
1001
0100 + 4
0101
+5
0110
–7
1000
–8
0111
+6
+7
ModularArithmetic
18
multiplication
5
x4
20
4
0101
x0100
00010100
-3
x7
-21
-2
1101
x0111
11101011
–1
–2
1111
1110
–3
–4
0
+1
0000
0001
1101
+2
0010
+3
1100
0011
– 5 1011
1010
–6
1001
0100 + 4
0101
+5
0110
–7
1000
–8
0111
+6
+7
ModularArithmetic
19
multiplication
5
x5
25
-7
0101
x0101
00011001
-2
x6
-12
4
1110
x0110
11110100
–1
–2
1111
1110
–3
–4
0
+1
0000
0001
1101
+2
0010
+3
1100
0011
– 5 1011
1010
–6
1001
0100 + 4
0101
+5
0110
–7
1000
–8
0111
+6
+7
ModularArithmetic
20
Convert/castsignednumbertolarger type.
00000010
8-bit2
________00000010
16-bit2
11111100
8-bit-4
________11111100
16-bit-4
Rule/name?
21
CastingIntegersinC
!!!
Numberliterals:37 issigned,37U isunsigned
IntegerCasting:bitsunchanged,justreinterpreted.
Explicitcasting:
int tx = (int) 73U;
// still 73
unsigned uy = (unsigned) -4; // big positive #
Implicitcasting:
Actuallydoes
tx = 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
!!!
MoreImplicitCastinginC
Ifyoumixunsignedand signed inasingleexpression,then
signedvaluesareimplicitlycasttounsigned.
Howaretheargument
bitsinterpreted?
Argument1
Op
0
==
-1
<
-1
<
2147483647
<
2147483647U
<
-1
<
(unsigned)-1 <
2147483647
<
2147483647
<
Argument2
0U
0
0U
-2147483648
-2147483648
-2
-2
2147483648U
(int)2147483648U
Type
unsigned
signed
unsigned
Note: Tmin =-2,147,483,648Tmax =2,147,483,647
Result
1
1
0
24
© Copyright 2025 Paperzz