You are on page 1of 38

Integers

Chapter2ofB&O

SomenotesadoptedfromBryantandOHallaron

Encoding Integers
Unsigned
B2U(X )

w1

xi 2

Twos Complement
B2T (X ) xw1 2

i0

w1

w2

xi 2 i

i0

short int x = 15213;


short int y = -15213;

Sign
Bit

Cshort 2byteslong
x
y

Decimal
15213
-15213

Hex
3B 6D
C4 93

Binary
00111011 01101101
11000100 10010011

SignBit
For2scomplement,mostsignificantbitindicatessign
0fornonnegative
1fornegative

Encoding Example (Cont.)


x =
y =
Weight
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
-32768
Sum

15213: 00111011 01101101


-15213: 11000100 10010011
15213
1
1
0
0
1
4
1
8
0
0
1
32
1
64
0
0
1
256
1
512
0
0
1
2048
1
4096
1
8192
0
0
0
0
15213

-15213
1
1
1
2
0
0
0
0
1
16
0
0
0
0
1
128
0
0
0
0
1
1024
0
0
0
0
0
0
1
16384
1 -32768
-15213

X
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

B2U(X)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

B2T(X)
0
1
2
3
4
5
6
7
8
7
6
5
4
3
2
1

Numeric Ranges
UnsignedValues
UMin = 0
0000

TwosComplementValues
TMin = 2w1
1000

UMax = 2w 1
1111

TMax =
0111

OtherValues
Minus1
1111

Values for W = 16
UMax
TMax
TMin
-1
0

Decimal
65535
32767
-32768
-1
0

Hex
FF FF
7F FF
80 00
FF FF
00 00

Binary
11111111 11111111
01111111 11111111
10000000 00000000
11111111 11111111
00000000 00000000

2w1 1

Values for Different Word Sizes


W
UMax
TMax
TMin

8
255
127
-128

16
65,535
32,767
-32,768

32
4,294,967,295
2,147,483,647
-2,147,483,648

Observations
|TMin|=TMax +1
Asymmetricrange

UMax =2*TMax +1

64
18,446,744,073,709,551,615
9,223,372,036,854,775,807
-9,223,372,036,854,775,808

CProgramming
#include <limits.h>
Declaresconstants,e.g.,
ULONG_MAX
LONG_MAX
LONG_MIN

Valuesplatformspecific

Casting Signed to Unsigned


CAllowsConversionsfromSignedtoUnsigned
short int
x = 15213;
unsigned short int ux = (unsigned short) x;
short int
y = -15213;
unsigned short int uy = (unsigned short) y;

ResultingValue
Nochangeinbitrepresentation
Nonnegativevaluesunchanged
ux =15213

Negativevalueschangeinto(large)positivevalues
uy =50323

Relation between Signed & Unsigned


Twos Complement

Unsigned

T2U
T2B

B2U

ux

X
Maintain Same Bit Pattern

w1
ux + + +

0
+++

+++

-++

+2w1 2w1 = 2*2w1 = 2w

x
ux
w
x 2

x0
x0

Illustration
2sComp. Unsigned
OrderingInversion
Negative BigPositive
TMax

2s Comp.
Range

0
1
2

TMin

UMax
UMax 1

TMax + 1
TMax

Unsigned
Range

Relation Between Signed & Unsigned


Weight
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
Sum

-15213
1
1
1
2
0
0
0
0
1
16
0
0
0
0
1
128
0
0
0
0
1
1024
0
0
0
0
0
0
1 16384
1 -32768
-15213

uy = y+2*32768

50323
1
1
1
2
0
0
0
0
1
16
0
0
0
0
1
128
0
0
0
0
1
1024
0
0
0
0
0
0
1
16384
1
32768
50323

= y+65536

Signed vs. Unsigned in C


Constants
Bydefaultareconsideredtobesignedintegers
UnsignedifhaveUassuffix
0U, 4294967259U

Casting
Explicitcastingbetweensigned&unsigned
int tx, ty;
unsigned ux, uy;
tx = (int) ux;
uy = (unsigned) ty;

Implicitcastingalsooccursviaassignmentsandprocedurecalls
tx = ux;
uy = ty;

Casting Surprises
ExpressionEvaluation
Ifmixunsignedandsignedinsingleexpression,signedvaluesimplicitlycast
tounsigned
Includingcomparisonoperations<,>,==,<=,>=
ExamplesforW =32

Constant1

Constant2

Relation

00
0U0U
-1-1
00
-1-1
0U0U
2147483647
-2147483648
2147483647
-2147483648
2147483647U -2147483648
-2147483648
2147483647U
-1-1
-2-2
(unsigned)-1-1-2-2
(unsigned)
2147483647 2147483648U
2147483648U
2147483647
2147483647 (int)
(int)2147483648U
2147483648U
2147483647

==
<
>
>
<
>
>
<
>

Evaluation
unsigned
signed
unsigned
signed
unsigned
signed
unsigned
unsigned
signed

Sign Extension
Task:
Givenwbitsignedintegerx
Convertittow+kbitintegerwithsamevalue

Rule:
Makek copiesofsignbit:
X =xw1,,xw1,xw1,xw2,,x0
w

k copies of MSB

Sign Extension Example


short int x = 15213;
int
ix = (int) x;
short int y = -15213;
int
iy = (int) y;

x
ix
y
iy

Decimal
Hex
15213
3B
15213 00 00 3B
-15213
C4
-15213 FF FF C4

6D
6D
93
93

Binary
00111011
00000000 00000000 00111011
11000100
11111111 11111111 11000100

01101101
01101101
10010011
10010011

Convertingfromsmallertolargerintegerdatatype
Cautomaticallyperformssignextension

Justification For Sign Extension


ProveCorrectnessbyInductiononk
InductionStep:extendingbysinglebitmaintainsvalue
w
X

-+


w+1

Keyobservation:
2w1 =2w +2w1
Lookatweightofupperbits:
X
X

2w1 xw1
2w xw1 +2w1 xw1

2w1 xw1

Beware When Using Unsigned


Dont UseJustBecauseNumberNonzero
Easytomakemistakes
for (i = cnt-2; i >= 0; i--)
a[i] += a[i+1];

Negating with Complement & Increment


Claim:FollowingHoldsfor2sComplement
~x + 1 == -x

Complement
Observation:~x + x == 1111112 == -1

Increment

10011101

+ ~x

01100010

-1

11111111

~x + x + (-x + 1) == -1 + (-x + 1)
~x + 1
==
-x

Comp. & Incr. Examples


x = 15213
Decimal
x
15213
~x
-15214
~x+1 -15213
y
-15213

Hex
3B 6D
C4 92
C4 93
C4 93

Binary
00111011 01101101
11000100 10010010
11000100 10010011
11000100 10010011

0
0
~0
~0+1

Decimal
0
-1
0

Hex
00 00
FF FF
00 00

Binary
00000000 00000000
11111111 11111111
00000000 00000000

Unsigned Addition
u

u+v

UAddw(u , v)

Operands: w bits
+

True Sum: w+1 bits


Discard Carry: w bits

StandardAdditionFunction
Ignorescarryoutput

ImplementsModularArithmetic
s =

UAddw(u ,v) = u +v mod2w


u v
UAdd w (u,v)
w
u v 2

u v 2w
u v 2w

Visualizing Integer Addition


IntegerAddition
4bitintegersu,v
Computetruesum
Add4(u ,v)
Valuesincrease
linearlywithu and
v
Formsplanar
surface

Add4(u , v)
Integer Addition

32
28
24
20
16

14

12

12
10

8
8
4

4
0

2
6

10

0
12

14

Visualizing Unsigned Addition


WrapsAround

Overflow

Iftruesum2w
Atmostonce
True Sum
2w+1

UAdd4(u , v)

16
14

Overflow

12
10
8

2w

14

12
10

4
8
2

Modular Sum

4
0

2
6

10

0
12

14

Mathematical Properties
ModularAddition
Closedunderaddition
0 UAddw(u ,v) 2w 1

Commutative
UAddw(u ,v) = UAddw(v ,u)

Associative
UAddw(t,UAddw(u ,v)) = UAddw(UAddw(t,u ),v)

0isadditiveidentity
UAddw(u ,0) = u

Everyelementhasadditiveinverse
Let UCompw(u ) = 2w u
UAddw(u ,UCompw(u )) = 0

Twos Complement Addition


u

u+v

TAddw(u , v)

Operands: w bits
+

True Sum: w+1 bits


Discard Carry: w bits

TAddandUAddhaveIdenticalBitLevelBehavior
Signedvs.unsignedadditioninC:
int s, t, u, v;
s = (int) ((unsigned) u + (unsigned) v);
t = u + v
Willgive s == t

Characterizing TAdd
Functionality

True Sum

Truesumrequiresw+1
bits
DropoffMSB
Treatremainingbitsas
2scomp.integer
PosOver

0 1111

PosOver

<0
NegOver

>0

TAdd Result

0 1000

2w 1

0111

0 0000

0000

1 1000

2w 1

1 0000

2w

TAdd(u , v)
>0
v
<0

2w1

1000
NegOver

u v 2 w 1 u v TMin w (NegOver)

TAddw (u,v) u v
TMinw u v TMax w
u v 2 w 1 TMax w u v (PosOver)

Visualizing 2s Comp. Addition


Values
4bittwoscomp.
Rangefrom8to+7

NegOver

TAdd4(u , v)

WrapsAround
Ifsum 2w1
Becomesnegative
Atmostonce

Ifsum<2w1
Becomespositive
Atmostonce

8
6
4
2
0

-2

4
2

-4
0
-6

-2

-8

-4
-8

-6

-4

-6
-2

-8
6

PosOver

Detecting 2s Comp. Overflow


Task
Given s =TAddw(u ,v)
Determineifs= Addw(u ,v)
Example
int s, u, v;
s = u + v;

2w1
PosOver

2w 1
0

NegOver

Claim
Overflowiffeither:
u,v <0,s 0
u,v 0,s <0

(NegOver)
(PosOver)

ovf = (u<0 == v<0) && (u<0 != s<0);

Multiplication
ComputingExactProductofwbitnumbersx,y
Eithersignedorunsigned
Ranges
Unsigned:0x*y(2w 1)2 =22w 2w+1 +1
Upto2wbits

Twoscomplementmin:x*y(2w1)*(2w11)=22w2 +2w1
Upto2w1bits

Twoscomplementmax:x*y(2w1) 2 =22w2
Upto2wbits,butonlyfor(TMinw)2

MaintainingExactResults
Wouldneedtokeepexpandingwordsizewitheachproduct
computed
Doneinsoftwarebyarbitraryprecisionarithmeticpackages
(GMP,BigNum,etc.)

Unsigned Multiplication in C
u

Operands: w bits
*

True Product: 2*w bits u v

UMultw(u , v)

Discard w bits: w bits

StandardMultiplicationFunction
Ignoreshighorderw bits

ImplementsModularArithmetic
UMultw(u ,v)

= u v mod2w

Unsigned vs. Signed Multiplication


UnsignedMultiplication
unsigned ux = (unsigned) x;
unsigned uy = (unsigned) y;
unsigned up = ux * uy
Truncatesproducttowbitnumberup =UMultw(ux,uy)
Modulararithmetic:up =ux uy mod2w

TwosComplementMultiplication
int x, y;
int p = x * y;
Computeexactproductoftwowbitnumbersx,y
Truncateresulttowbitnumberp =TMultw(x,y)

Unsigned vs. Signed Multiplication


UnsignedMultiplication
unsigned ux = (unsigned) x;
unsigned uy = (unsigned) y;
unsigned up = ux * uy

TwosComplementMultiplication
int x, y;
int p = x * y;

Relation
Signedmultiplicationgivessamebitlevelresultas
unsigned
up == (unsigned) p

Power-of-2 Multiply with Shift


Operation
u << k givesu * 2k
Bothsignedandunsigned
u

2k

0 0 1 0 0 0

Operands: w bits
*

True Product: w+k bits


Discard k bits: w bits

u 2k

UMultw(u , 2k)

0 0 0
0 0 0

TMultw(u , 2k)

Examples
u << 3
== u * 8
u << 5 - u << 3 ==
u * 24
Mostmachinesshiftandaddmuchfasterthanmultiply
Compilergeneratesthiscodeautomatically

Unsigned Power-of-2 Divide with Shift


QuotientofUnsignedbyPowerof2
u >> k gives u / 2k
Useslogicalshift
k
u

Binary Point

Operands:
/

Division:
Result:

x
x >> 1
x >> 4
x >> 8

2k

0 0 1 0 0 0

u / 2k

u / 2k

Division
15213
7606.5
950.8125
59.4257813

Computed
15213
7606
950
59

Hex
3B 6D
1D B6
03 B6
00 3B

Binary
00111011 01101101
00011101 10110110
00000011 10110110
00000000 00111011

Signed Power-of-2 Divide with Shift


QuotientofSignedbyPowerof2
x >> k gives x / 2k
Usesarithmeticshift
Roundswrongdirectionwhenu < 0
k
x

Binary Point

Operands:
/

x / 2k

Division:
Result:

y
y >> 1
y >> 4
y >> 8

2k

RoundDown(x / 2k)
Division
-15213
-7606.5
-950.8125
-59.4257813

0 0 1 0 0 0
0

Computed
-15213
-7607
-951
-60

Hex
C4 93
E2 49
FC 49
FF C4

Binary
11000100 10010011
11100010 01001001
11111100 01001001
11111111 11000100

Correct Power-of-2 Divide


QuotientofNegativeNumberbyPowerof2
Want x / 2k (RoundToward0)
Computeas (x+2k-1)/ 2k
InC:(x + (1<<k)-1) >> k
Biasesdividendtoward0

Case1:Norounding
Dividend:

u
+2k +1

k
1

2k

u / 2k
Biasing has no effect

0 0 0

0 0 0 1 1 1
1

Divisor:

1 1 1

Binary Point

0 0 1 0 0 0
0 1 1 1
1

. 1 1 1

Correct Power-of-2 Divide (Cont.)


Case 2: Rounding
k
Dividend:

x
+2k +1

0 0 0 1 1 1
1

Incremented by 1
Divisor:

2k

x / 2k

Binary Point

0 0 1 0 0 0
0 1 1 1
1

Biasing adds 1 to final result

Incremented by 1

C Puzzles
Assumemachinewith32bitwordsize,twoscomplement
integers
ForeachofthefollowingCexpressions,either:
Arguethatitistrueforallargumentvalues
Giveexamplewherenottrue
x < 0
Initialization

ux >= 0
x & 7 == 7

int x = foo();
int y = bar();
unsigned ux = x;
unsigned uy = y;

((x*2) < 0)
(x<<30) < 0

ux > -1
x > y

-x < -y

x * x >= 0
x > 0 && y > 0 x + y > 0
x >= 0

-x <= 0

x <= 0

-x >= 0

C Puzzle Answers
Assumemachinewith32bitwordsize,twoscomp.
integers
TMinmakesagoodcounterexampleinmanycases

False:

TMin

True:

0 = UMin

True:

x1 = 1

False:

False:

-1, TMin

False:

30426

x + y > 0

False:

TMax, TMax

-x <= 0

True:

TMax < 0

-x >= 0

False:

TMin

x < 0

ux >= 0

x & 7 == 7

ux > -1

x > y

x * x >= 0

x > 0 && y > 0

x >= 0

x <= 0

((x*2) < 0)

(x<<30) < 0

-x < -y

ezThreeFourths
/*
*ezThreeFourths multipliesby3/4roundingtoward0,
*ShouldexactlyduplicateeffectofCexpression(x*3/4),
*includingoverflowbehavior.
*Examples:ezThreeFourths(11)=8
*ezThreeFourths(9)=6
*ezThreeFourths(1073741824)=268435456(overflow)
*Legalops:!~&^|+<<>>
*Maxops:12
*Rating:3
*/
int ezThreeFourths(int x){

ezThreeFourths
/*
*ezThreeFourths multipliesby3/4roundingtoward0,
*ShouldexactlyduplicateeffectofCexpression(x*3/4),
*includingoverflowbehavior.
*Examples:ezThreeFourths(11)=8
*ezThreeFourths(9)=6
*ezThreeFourths(1073741824)=268435456(overflow)
*Legalops:!~&^|+<<>>
*Maxops:12
*Rating:3
*/
int ezThreeFourths(int x){
int temp=x+x+x;
int sign=temp>>31;
int temp2=sign&((1<<2)+(~1+1));
return(temp+temp2)>>2;
}

You might also like