46
Samira Khan University of Virginia Jan 31, 2017 Binary Operations CS 3330

Binary Operations - University of Virginia

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

SamiraKhanUniversityofVirginia

Jan31,2017

BinaryOperationsCS3330

AGENDA

• Logistics

• ReviewfromlastLecture

• BinaryOperations– LogicalOperations– BitwiseOperations– Examples

2

Feedbacks

• Quizzesarehard– Usethebook,lectures,internet,whateveryoucan– Pastquizzesareavailableonline

• Forthequizquestionwith:typedef struct bar{intx;}foo;Itriedcompilingstruct foo*c;inC,anditcompiledfine.Sowhyisitwrong?– Droppedit– Goodcatch– AskinPiazza,sothatotherscanlearn,too

3

Feedbacks

• Isastringstillastringifitisexpressedinbits?thatseemslikemoreofaphilosophicalquestiontomeI'mreferringtothequizquestion– Yes– Thereisno“abcde…”– Everythingisjust0sand1s– Itisjusthowyouinterpretit

4

AGENDA

• Logistics

• ReviewfromlastLecture

• BinaryOperations– LogicalOperations– BitwiseOperations– Examples

5

UndefinedBehavior

• CFAQdefinition:• Anythingatallcanhappen– Standardimposesnorequirements;– Programmayfailtocompile,– oritmayexecuteincorrectly,– oritmaydoexactlywhattheprogrammerintended

6

AddingonetoINT_MAXifweaddonetothelargestrepresentableinteger,istheresultnegative?

#include<limits.h>#include<stdio.h>

int main(void){printf ("%d\n",(INT_MAX+1)<0);return0;}

7

Undefined,outputcouldbezeroorone

MoreUndefinedBehavior• Attemptingtomodifyastringliteral– char*p="wikipedia";//validC– p[0]='W';//undefinedbehavior

• Integerdivisionbyzero– int x=1;– return x/0;//undefinedbehavior

• Certainpointeroperations– int arr[4]={0,1,2,3};– int *p=arr +5; //undefinedbehavior

• Incrementandassignment– i =i+++1;//undefinedbehavior

8

UndefinedBehavior

• Pros:– Simplifies thecompiler’sjob– Generatesveryefficientcode– Example:incrementINT_MAX• Doesnotneedtoworryaboutoverflowsandresultbecomenegative

• Cons:–Misbehavedprograms– Securityissues– Example:Arrayoutofbound

9

AGENDA

• Logistics

• ReviewfromlastLecture

• BinaryOperations– LogicalOperations– BitwiseOperations– Examples

10

Howdodigitalcomputersrepresentnumbers?

• Madeoftransistors(thinkasaswitch)• Haveonlytwostates:ON,OFF

11

• Canonlyuse0and1torepresentnumbers• 3à 0011,10à 1010

BinaryOperations• Weneedtooperateonthesebinarynumbers• ArithmeticOperations– ADD,SUB,MUL,DIV

• LogicalOperations• AND,OR,NOT

• BitwiseOperations– AND,OR,NOT,XOR,SHIFT

12

LogicalOperations

13

Operator Description ExampleA=2,B=0

LogicalAND(&&)

Boththeoperandsarenon-zeroà conditionbecomes

true

A&&B=False/0

LogicalOR(||)

Anyofthetwooperandsisnon-zeroà thecondition

becomestrue

A||B=1/true

LogicalNOT(!/~)

Reversethelogicalstate !(A&&B)= 1/true

LogicalOperations

14

Operator Description ExampleA=2,B=0

LogicalAND(&&)

Boththeoperandsarenon-zeroà conditionbecomes

true

A&&B=False/0

LogicalOR(||)

Anyofthetwooperandsisnon-zeroà thecondition

becomestrue

A||B=1/true

LogicalNOT(!/~)

Reversethelogicalstate !(A&&B)= 1/true

LogicalOperations

15

Operator Description ExampleA=2,B=0

LogicalAND(&&)

Boththeoperandsarenon-zeroà conditionbecomes

true

A&&B=False/0

LogicalOR(||)

Anyofthetwooperandsisnon-zeroà thecondition

becomestrue

A||B=1/true

LogicalNOT(!/~)

Reversethelogicalstate !(A&&B)= 1/true

LogicalOperations

16

Operator Description ExampleA=2,B=0

LogicalAND(&&)

Boththeoperandsarenon-zeroà conditionbecomes

true

A&&B=False/0

LogicalOR(||)

Anyofthetwooperandsisnon-zeroà thecondition

becomestrue

A||B=1/true

LogicalNOT(!/~)

Reversethelogicalstate !(A&&B)= 1/true

Example:Short-Circuit#include<stdio.h>int zero(){printf("zero()\n");return0;}int one(){printf("one()\n");return1;}

int main(){printf(">␣%d\n",zero()&&one());printf(">␣%d\n",one()&&zero());return0;}

17

OUTPUTzero()>0one()zero()>0

AGENDA

• Logistics

• ReviewfromlastLecture

• BinaryOperations– LogicalOperations– BitwiseOperations– Examples

18

X Y X ANDY XOR Y XXORY NOT X0 0 0 0 0 10 1 0 1 1 11 0 0 1 1 01 1 1 1 0 0

19

BitwiseOperations

X Y X ANDY XOR Y XXORY NOT X0 0 0 0 0 10 1 0 1 1 11 0 0 1 1 01 1 1 1 0 0

20

BitwiseOperations

Operatesoneachbit

X Y X ANDY XOR Y XXORY NOT X0 0 0 0 0 10 1 0 1 1 11 0 0 1 1 01 1 1 1 0 0

21

BitwiseOperations

Operatesoneachbit

X Y X ANDY XOR Y XXORY NOT X0 0 0 0 0 10 1 0 1 1 11 0 0 1 1 01 1 1 1 0 0

22

BitwiseOperations

Operatesoneachbit

X Y X ANDY XOR Y XXORY NOT X0 0 0 0 0 10 1 0 1 1 11 0 0 1 1 01 1 1 1 0 0

23

BitwiseOperations

Operatesoneachbit

24

BitwiseOperations

0010&0100------------0000

0010|0100------------0110

0010^ 0100------------

0110

~0100------------

1011

0010>>0001------------

0001

Whataboutnegativenumbers?

AND OR XOR NOT SHIFT

25

SHIFTBitwiseOperations

• WhatvalueshouldbeplacedintheMSB?• −10>>1==???

• -10=1111…11110110• -10>>1==?111…11111011

• Option1:copysignbità Arithmeticshift• Option2:alwayskeepzeroà Logicalshift

SignedandUnsignedShift• /*signed*/int x=−10;• /*arithmetic:*/• x>>1==−5• x>>4==−1

• unsignedint y=0xFFFFFFF6;• /*logical*/• y>>1==0x7FFFFFFB• y>>4==0x0FFFFFFF

26

UndefinedBehaviorwithSHIFTS

• 0>>32à undefinedbehavior

• 0<<32à undefinedbehavior

• (long)0>>32à okay

• (long)0>>64à undefinedbehavior

27

AGENDA

• Logistics

• ReviewfromlastLecture

• BinaryOperations

– LogicalOperations– BitwiseOperations– Examples

28

RECAP:BinaryOperations

• BitwiseOperations– AND,OR,NOT,XOR,SHIFT

29

WhydoBitManipulation?

WhydoBitManipulation?• Fasterthanmanycomplexoperations– DIV25-123cycles– ADD/AND/CMP/OR/SUB/XOR1cycle

• Examples:– Supposeyouaredesigningareliablesystem,wanttodetectifanybitflipped

– Parity:countthenumberofones,store1ifeven– Howmanyonesarethereinanumber?

– SupposeyouwanttomakeDIVfasterifitisapoweroftwo

– Isanumberapoweroftwo?

30Intel®64andIA-32ArchitecturesOptimizationReferenceManual

BuildingBlocksofBitManipulation• Setabit,keepotherbitsunchanged– 0à 1;1à 1

• Reset/Clearabit,keepotherbitsunchanged– 1à 0;0à 0

• Toggleabit,keepotherbitsunchanged– 1à 0;0à 1

• Extractandshift– 10101111 10101010à 0000000000001111

31

BuildingBlocksofBitManipulation• Setabit– 0à 1;1à 1– X|1– Example:– Setthethirdbitof1010– 1010|0100=1110– X3X2X1X0 |0100=X31X1X0

32

BuildingBlocksofBitManipulation• Reset/Clearabit– 1à 0;0à 0– X&0– Example:– Clearthethirdbitof1110– 1110&1011=1010– X3X2X1X0 & 1011=X30X1X0

33

BuildingBlocksofBitManipulation• Toggleabit,keepotherbitsunchanged– 1à 0;0à 1– X^1– Example:– Togglethethirdbitofthebitvector– 1110^0100=1010– 1010^0100=1110– X3X2X1X0 |0100=X3𝑿𝟐X1X0

34

BuildingBlocksofBitManipulation• Extractandshift– 10101111 10101010à 0000000000001111

–Mask:X&0x0F00=0000X3X2X1X0 00000000– Shift:X>>8=000000000000X3X2X1X

35

ExampleProblems• Isanybitsetinthebitvector?

• Howmanybitsareset?

• HowtomanipulatecolorsinRGB?

36

Isanybitsetinthebitvector?

• NaïveSolution

• Shiftabitandcheckifitis1• (X&1)|((X>>1)&1)|((X>>2)&1)…• 00110010&1=0• 00011001&1=1• 00001100&1=0• ....

• Anyothersolution? 37

Isanybitsetinthebitvector?• Operateonlyonhalf• Assume16bitsinteger• A =(X>>8)|X• TaketheupperhalfandorwithX• IfanybitinXisset,lowerhalfofawillhaveasetbit

• X=0000010000000000

38

0000000000000100X>>8|0000010000000000X--------------------------------------- ------ 00000100A

• A=(X>>8)|X• A=(A>>4)|A• A=(A>>2)|A• A=(A>>1)|A• returnA&1

39

----- ------ 00000000A>>4| ----- ------ 00000100A--------------------------------------- ----- ---- 0100A

Isanybitsetinthebitvector?

• A=(X>>8)|X• A=(A>>4)|A• A=(A>>2)|A• A=(A>>1)|A• returnA&1

40

----- ------ ----- 0001A>>2| ----- ------ ----- 0100A--------------------------------------- ----- ---- -- 01A

Isanybitsetinthebitvector?

• A=(X>>8)|X• A=(A>>4)|A• A=(A>>2)|A• A=(A>>1)|A• returnA&1

41

----- ------ ----- -- 00A>>1| ----- ------ ----- -- 01A--------------------------------------- ----- ---- -- - 1A

Isanybitsetinthebitvector?

ExampleProblems• Isanybitsetinthebitvector?

• Howmanybitsareset?

• HowtomanipulatecolorsinRGB?

42

CountSetbits

• Count=X&1• Count+=(X>>1)&1• Count+=(X>>2)&1• …

43

ExampleProblems• Isanybitsetinthebitvector?

• Howmanybitsareset?

• HowtomanipulatecolorsinRGB?

44

HowtomanipulatecolorsinRGB?• RGB8bits– Eachcolorisrepresentedusing8bit– 0to255

• 32bits:0x00BBGG RR• int blueMask =0xFF0000int greenMask =0xFF00int redMask =0xFF;int r=12,g=13,b=14;int bgrValue =(b<<16)+(g<<8)+r;printf("blue:%d\n”,((bgrValue &blueMask)>>16));printf("red:%d\n”,((bgrValue &redMask)));printf("green:%d\n”,((bgrValue &greenMask)>>8));

45

SamiraKhanUniversityofVirginia

Jan31,2017

BinaryOperationsCS3330