comp 21000 topics numeric encodings unsigned & two’s complement programming implications c...
TRANSCRIPT
Comp 21000Comp 21000
TopicsTopics Numeric Encodings
Unsigned & Two’s complement
Programming ImplicationsC promotion rules
Basic operationsAddition, negation, multiplication
Programming ImplicationsConsequences of overflowUsing shifts to perform power-of-2 multiply/divide
IntegersSpring 2015
IntegersSpring 2015
– 2 – COMP 21000, S’15
C PuzzlesC Puzzles Answers on the last slide Assume machine with 32 bit word size, two’s complement
integers For each of the following C expressions, either:
Argue that is true for all argument valuesGive example where not true
• x < 0 ((x*2) < 0)
• ux >= 0
• x & 7 == 7 (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
int x = foo();
int y = bar();
unsigned ux = x;
unsigned uy = y;
Initialization
– 3 – COMP 21000, S’15
Encoding IntegersEncoding Integers
short int x = 15213; short int y = -15213;
C short 2 bytes long
Sign BitSign Bit For 2’s complement, most significant bit indicates sign
0 for nonnegative1 for negative
Unsigned Two’s Complement
SignBit
Decimal Hex Binaryx 15213 3B 6D 00111011 01101101y -15213 C4 93 11000100 10010011
– 4 – COMP 21000, S’15
Negative numbersNegative numbers
Problem: how do we represent negative numbers?Problem: how do we represent negative numbers? Sign-magnitude.
Wastes space (range decreases)Not used anymore (was used on a few IBM mainframes in the
dark ages)
2’s complementSpace efficientArithmetic works well
– 5 – COMP 21000, S’15
The structure of a signed integer(if we’re using sign-magnitude)The structure of a signed integer(if we’re using sign-magnitude)
This is no longer used!
– 6 – COMP 21000, S’15
Instead of using sign magnitude…Instead of using sign magnitude…
We’ll break the number line in the middle
– 7 – COMP 21000, S’15
two’s complementtwo’s complement
Note that negative numbers start with a 1, but starting with a 1 is not what makes the number negative.
Result is called 2’s complement.
There is an easy arithmetic way to convert numbers to their negative equivalent with 2’s complement.
…and shift the right part of the number line to the left side to get…
– 8 – COMP 21000, S’15
2’s complement2’s complement
Rule:Rule: Positive numbers: use the normal binary representation
(first bit must be 0 if the number is positive). Negative numbers:
1. find positive binary representation of the number
2. Take the complement of the binary number.
3. Add 1 to the result.
+2 = 010
-2 = Complement: 101
Take result and add 1: 101
+ 1
110 = –2
– 9 – COMP 21000, S’15
2’s complement2’s complement
Rule:Rule: To find the value represented by a binary number that starts
with a 1 (i.e., a negative number) Take the complement of the binary number. Add 1 to the result. determine the decimal value
To find the value reprsented by 110
Take the Complement: 001
add 1 to the complement] + 1
find the decimal value 010 = +2
This is the absolute value
of 110
– 10 – COMP 21000, S’15
2’s complement range2’s complement range
There will be more negative numbers than positive There will be more negative numbers than positive numbers since 0 takes a positive space:numbers since 0 takes a positive space:
– 11 – COMP 21000, S’15
The signed integers for a four-bit cellThe signed integers for a four-bit cell
– 12 – COMP 21000, S’15
2’s complement range2’s complement range
Range for any cell size:Range for any cell size: Smallest number is 1000… 0 Largest number is 0111…..1 The magnitude of the smallest negative number is 1 greater
than the magnitude of the largest positive number. Example: 6-bit cell: -32 to 31
– 13 – COMP 21000, S’15
Converting 2’s complementConverting 2’s complement
If the number is positive, just convert directly to If the number is positive, just convert directly to decimal.decimal. 0101010 = 42
If the number is negative:If the number is negative: Take the 2’s complement, find decimal equivalent, negate Or find the magnitude by summing the place values of the
0’s in the original number, then add 1. 1101010
take complement: 0010101 add 1: 0010101 + 1 = 0010110 convert: 0010110 = 22 Answer: -22
– 14 – COMP 21000, S’15
Numeric RangesNumeric Ranges
Unsigned ValuesUnsigned Values UMin = 0
000…0
UMax = 2w – 1111…1
Two’s Complement ValuesTwo’s Complement Values TMin = –2w–1
100…0
TMax = 2w–1 – 1
011…1
Other ValuesOther Values Minus 1
111…1Decimal Hex Binary
UMax 65535 FF FF 11111111 11111111TMax 32767 7F FF 01111111 11111111TMin -32768 80 00 10000000 00000000-1 -1 FF FF 11111111 111111110 0 00 00 00000000 00000000
Values for W = 16
– 15 – COMP 21000, S’15
Values for Different Word SizesValues for Different Word Sizes
ObservationsObservations |TMin | = TMax +
1Asymmetric range
UMax = 2 * TMax + 1
C ProgrammingC Programming #include <limits.h>
K&R App. B11
Declares constants, e.g., ULONG_MAX LONG_MAX LONG_MIN
Values platform-specific
W8 16 32 64
UMax 255 65,535 4,294,967,295 18,446,744,073,709,551,615TMax 127 32,767 2,147,483,647 9,223,372,036,854,775,807TMin -128 -32,768 -2,147,483,648 -9,223,372,036,854,775,808
– 16 – COMP 21000, S’15
Unsigned & Signed Numeric ValuesUnsigned & Signed Numeric Values EquivalenceEquivalence
Same encodings for nonnegative values
UniquenessUniqueness Every bit pattern represents
unique integer value Each representable integer
has unique bit encoding
Can Invert MappingsCan Invert Mappings U2B(x) = B2U-1(x)
Bit pattern for unsigned integer
T2B(x) = B2T-1(x)Bit pattern for two’s comp
integer
X B2T(X)B2U(X)0000 00001 10010 20011 30100 40101 50110 60111 7
–88–79–610–511–412–313–214–115
10001001101010111100110111101111
01234567
– 17 – COMP 21000, S’15
short int x = 15213; unsigned short int ux = (unsigned short) x; short int y = -15213; unsigned short int uy = (unsigned short) y;
Casting Signed to UnsignedCasting Signed to Unsigned
C Allows Conversions from Signed to UnsignedC Allows Conversions from Signed to Unsigned
Resulting ValueResulting Value No change in bit representation Nonnegative values unchanged
ux = 15213
Negative values change into (large) positive valuesuy = 50323
– 18 – COMP 21000, S’15
T2U
T2B B2U
Two’s Complement Unsigned
Maintain Same Bit Pattern
x uxX
+ + + + + +• • •
- + + + + +• • •
ux
x-
w–1 0
+2w–1 – –2w–1 = 2*2w–1 = 2w
Relation between Signed & UnsignedRelation between Signed & Unsigned
– 19 – COMP 21000, S’15
Relation Between Signed & UnsignedRelation Between Signed & Unsigned
uy = y + 2 * 32768 = y + 65536 50323 = -15213 + 65536
Weight -15213 503231 1 1 1 12 1 2 1 24 0 0 0 08 0 0 0 0
16 1 16 1 1632 0 0 0 064 0 0 0 0
128 1 128 1 128256 0 0 0 0512 0 0 0 0
1024 1 1024 1 10242048 0 0 0 04096 0 0 0 08192 0 0 0 0
16384 1 16384 1 1638432768 1 -32768 1 32768
Sum -15213 50323The bits that are
stored:1100010010010011
The bits that are stored:
1100010010010011
– 20 – COMP 21000, S’15
Signed vs. Unsigned in CSigned vs. Unsigned in C
ConstantsConstants By default are considered to be signed integers Unsigned if have “U” as suffix
0U, 4294967259U
CastingCasting Explicit casting between signed & unsigned same as U2T and
T2Uint tx, ty;unsigned ux, uy;tx = (int) ux;uy = (unsigned) ty;
Implicit casting also occurs via assignments and procedure callstx = ux;uy = ty;
– 21 – COMP 21000, S’15
0 0U == unsigned
-1 0 < signed
-1 0U > unsigned
2147483647 -2147483648 > signed
2147483647U -2147483648 <unsigned
-1 -2 > signed
(unsigned) -1 -2 >unsigned
2147483647 2147483648U <unsigned
2147483647 (int) 2147483648U > signed
Casting SurprisesCasting SurprisesExpression EvaluationExpression Evaluation
If mix unsigned and signed in single expression, signed values implicitly cast to unsigned
Including comparison operations <, >, ==, <=, >= Examples for number of bits W = 32
ConstantConstant11 ConstantConstant22 RelationRelation EvaluationEvaluation
0 0U
-1 0
-1 0U
2147483647 -2147483648
2147483647U -2147483648
-1 -2
(unsigned) -1 -2
2147483647 2147483648U
2147483647 (int) 2147483648U
(0x7FFFFFFF) (0x80000000)
How is this converted to int?
– 22 – COMP 21000, S’15
0
TMax
TMin
–1–2
0
UMaxUMax – 1
TMaxTMax + 1
2’s Comp.Range
UnsignedRange
Explanation of Casting SurprisesExplanation of Casting Surprises
2’s Comp. 2’s Comp. Unsigned Unsigned Ordering Inversion Negative Big Positive
– 23 – COMP 21000, S’15
Sign ExtensionSign Extension
Task:Task: Given w-bit signed integer x Convert it to w+k-bit integer with same value
Rule:Rule: Make k copies of sign bit: X = xw–1 ,…, xw–1 , xw–1 , xw–2 ,…, x0
k copies of MSB
• • •X
X • • • • • •
• • •
w
wk
– 24 – COMP 21000, S’15
Sign Extension ExampleSign Extension Example
Converting from smaller to larger integer data type C automatically performs sign extension
short int x = 15213; int ix = (int) x; short int y = -15213; int iy = (int) y;
Decimal Hex Binaryx 15213 3B 6D 00111011 01101101ix 15213 00 00 3B 6D 00000000 00000000 00111011 01101101y -15213 C4 93 11000100 10010011iy -15213 FF FF C4 93 11111111 11111111 11000100 10010011
– 25 – COMP 21000, S’15
Justification For Sign ExtensionJustification For Sign ExtensionProve Correctness by Induction on Prove Correctness by Induction on kk
Induction Step: extending by single bit maintains value
Key observation: –2w–1 = –2w +2w–1
Look at weight of upper bits: X –2w–1 xw–1
X –2w xw–1 + 2w–1 xw–1 = –2w–1 xw–1 - • • •X
X - + • • •
w+1
w
– 26 – COMP 21000, S’15
Why Should I Use Unsigned?Why Should I Use Unsigned?
DonDon’’tt Use Just Because Number Nonzero Use Just Because Number Nonzero C compilers on some machines generate less efficient code
unsigned i;for (i = 1; i < cnt; i++) a[i] += a[i-1];
Easy to make mistakes: think about truncationfor (i = cnt-2; i >= 0; i--) a[i] += a[i+1];
DoDo Use When Performing Modular Arithmetic Use When Performing Modular Arithmetic Multiprecision arithmetic Other esoteric stuff: flags, mainpulating registers, addresses
DoDo Use When Need Extra Bit Use When Need Extra Bit’’s Worth of Ranges Worth of Range Working right up to limit of word size
– 27 – COMP 21000, S’15
Negating with Complement & IncrementNegating with Complement & IncrementClaim: Following Holds for 2Claim: Following Holds for 2’’s Complements Complement
~x + 1 == -x
ComplementComplement Observation: ~x + x == 1111…112 == -1
IncrementIncrement ~x + x = - 1
~x + x + (-x + 1) == -1 + (-x + 1) ~x + 1 == -x
Warning: Be cautious treating Warning: Be cautious treating intint’’s as integerss as integers OK here
1 0 0 1 0 11 1 x
0 1 1 0 1 00 0~x+
1 1 1 1 1 11 1-1
– 28 – COMP 21000, S’15
Comp. & Incr. ExamplesComp. & Incr. Examples
Decimal Hex Binaryx 15213 3B 6D 00111011 01101101~x -15214 C4 92 11000100 10010010~x+1 -15213 C4 93 11000100 10010011y -15213 C4 93 11000100 10010011
x = 15213
Decimal Hex Binary0 0 00 00 00000000 00000000~0 -1 FF FF 11111111 11111111~0+1 0 00 00 00000000 00000000
0
– 29 – COMP 21000, S’15
Binary additionBinary addition
11
00 11 00 1 1 1 1
00 00 11 1 1 1 1
00 11 11 1010 1111
– 30 – COMP 21000, S’15
Carry bitCarry bit
Problem: cells have fixed number of bitsProblem: cells have fixed number of bits
If addition requires more bits, must If addition requires more bits, must carrycarry a bit out. Called a bit out. Called a a carry bitcarry bit or a or a carry outcarry out..
Example: 6-bit cell (assume unsigned)Example: 6-bit cell (assume unsigned)
0 1 0 1 1 00 1 0 1 1 0 1 1 1 0 1 0 581 1 1 0 1 0 58
1 0 0 0 1 01 0 0 0 1 0 0 1 1 1 0 1 +290 1 1 1 0 1 +29
0 0 1 1 1 0 0 01 1 1 0 0 0 1 1 0 1 0 1 1 1 870 1 0 1 1 1 87
Carry bit Carry bit
– 31 – COMP 21000, S’15
Binary subtractionBinary subtraction
00 11 1111 110 60 6
00 00 11 1 3 1 3
00 00 11 1 (6 – 3 = 3) 1 (6 – 3 = 3)
When the bottom bit is larger than the top bit, must When the bottom bit is larger than the top bit, must borrow from the next left position.borrow from the next left position.
– 32 – COMP 21000, S’15
Subtraction: Carry bitSubtraction: Carry bit
When subtract, may have to borrow.When subtract, may have to borrow.
If most significant bit needs a borrow, must If most significant bit needs a borrow, must carrycarry a bit in. a bit in. Called a Called a carry incarry in..
Set the Set the CC bit to indicate that the result is bit to indicate that the result is not validnot valid..
Example: 6-bit cell (assume Example: 6-bit cell (assume unsignedunsigned))
110 0 0 1 0 00 0 0 1 0 0 0 1 1 1 0 1 290 1 1 1 0 1 29
-- 1 0 0 1 0 0 1 0 0 1 0 0 1 1 1 0 1 01 1 1 0 1 0 –58–58
1 1 0 0 0 0 01 1 0 0 0 0 0 1 1 0 0 0 1 1 35? 1 1 0 0 0 1 1 35?
Carry bit Carry bit
– 33 – COMP 21000, S’15
02
46
810
1214
0
2
4
6
8
10
1214
0
4
8
12
16
20
24
28
32
Integer Addition
Visualizing Integer AdditionVisualizing Integer Addition
Integer AdditionInteger Addition 4-bit integers u, v Compute true sum
Add4(u , v)
Values increase linearly with u and v
Forms planar surface
May need extra bitLargest 4 bit
number = 1515 + 15 = 3030 = 11110 (5 bits)
Add4(u , v)
u
v
– 34 – COMP 21000, S’15
Unsigned AdditionUnsigned Addition
Standard Addition FunctionStandard Addition Function Ignores carry output
Implements Modular ArithmeticImplements Modular Arithmetics = UAddw(u , v) = u + v mod 2w
• • •
• • •
u
v+
• • •u + v
• • •
True Sum: w+1 bits
Operands: w bits
Discard Carry: w bits UAddw(u , v)
– 35 – COMP 21000, S’15
Unsigned AdditionUnsigned Addition
Explanation for resultsExplanation for results
1 1 1 1 151 1 1 1 15
1 1 1 11 1 1 1 15 15
1 1 1 1 1 0 301 1 1 0 30 30 30
1 0 0 0 01 0 0 0 0 2 244 = 16 = 16 ––1616
1 1 1 0 141 1 1 0 14 14 14
– 36 – COMP 21000, S’15
02
46
810
1214
0
2
4
6
8
10
1214
0
2
4
6
8
10
12
14
16
Visualizing Unsigned AdditionVisualizing Unsigned Addition
Wraps AroundWraps Around If true sum ≥ 2w
At most once
0
2w
2w+1
UAdd4(u , v)
u
v
True Sum
Modular Sum
Overflow
Overflow
– 37 – COMP 21000, S’15
Adding 2’s complementAdding 2’s complement
Just add as normal. Always works (ignore the carry bit).Just add as normal. Always works (ignore the carry bit).
0 0 1 +10 0 1 +1 0 1 10 1 1 +3 +3 1 1 01 1 0 –2 –2
0 1 00 1 0 + +22 1 1 01 1 0 – –22 0 1 10 1 1 + +33
0 1 1 +30 1 1 +3 0 0 1 0 0 1 +1 +1 0 0 1 +10 0 1 +1
1 1 0 –21 1 0 –2
1 1 01 1 0 – –22
1 0 0 –41 0 0 –4
– 38 – COMP 21000, S’15
Two’s Complement AdditionTwo’s Complement Addition
TAdd and UAdd have Identical Bit-Level BehaviorTAdd and UAdd have Identical Bit-Level Behavior Signed vs. unsigned addition in C:
int s, t, u, v;
s = (int) ((unsigned) u + (unsigned) v);
t = u + v Will give s == t
• • •
• • •
u
v+
• • •u + v
• • •
True Sum: w+1 bits
Operands: w bits
Discard Carry: w bits TAddw(u , v)
– 39 – COMP 21000, S’15
Status bitsStatus bits
CPU keeps track of 4 bits: CVZN bitsCPU keeps track of 4 bits: CVZN bits These are saved in a special register
A register has one word of storage
They are set when an arithmetic operation is performeda few other operations in assembly language will also set them
Carry: bit that is carried out of an addition overflow (v): set if the arithmetic overflows (see later slide) zero (z): set to 1 if the result of the arithmetic was zero,
otherwise the z bit is set to 0 negative (n): set to 1 if the result of the arithmetic is
negative, otherwise the n bit is set to 0
Flag: C V Z N
1 0 1 0
– 40 – COMP 21000, S’15
Status BitsStatus Bits
Example 1:Example 1:
1 0 1 01 0 1 0
+ 1 0 1 1+ 1 0 1 1
0 1 0 10 1 0 1
c: 1c: 1
z: 0z: 0
v: 1v: 1
n: 0n: 0
Example 2:Example 2:
1 0 1 01 0 1 0
+ 1 1 1 1+ 1 1 1 1
1 0 0 11 0 0 1
c: 1c: 1
z: 0z: 0
v: 0v: 0
n: 1n: 1
Example 3:Example 3:
0 0 0 10 0 0 1
+ 1 1 1 1+ 1 1 1 1
0 0 0 00 0 0 0
c: 1c: 1
z: 1z: 1
v: 0v: 0
n: 0n: 0
Example 4:Example 4:
1 0 0 11 0 0 1
+ 1 1 1 1+ 1 1 1 1
1 0 0 01 0 0 0
c: 1c: 1
z: 0z: 0
v: 0v: 0
n: 1n: 1
– 41 – COMP 21000, S’15
Overflow bitOverflow bit
What if the result is too big for the number of bits?What if the result is too big for the number of bits?
Have overflow.Have overflow.
Carry bit no longer indicates whether the sum is in Carry bit no longer indicates whether the sum is in range.range.
CPU contains a special bit called the overflow bit CPU contains a special bit called the overflow bit denoted by the letter Vdenoted by the letter V
If sum is out of range, V = 1If sum is out of range, V = 1
Otherwise V = 0Otherwise V = 0
– 42 – COMP 21000, S’15
Overflow bitOverflow bit
CPU will always set the V bit and continue. Does not CPU will always set the V bit and continue. Does not care if V = 1 or if V = 0.care if V = 1 or if V = 0.
Note that overflow cannot occur if:Note that overflow cannot occur if: Adding two numbers of different signs
Result must be smaller than either number
Subtracting two numbers of same signThis is the same as adding two numbers of different signs: x –
y = x + (–y)
– 43 – COMP 21000, S’15
Detecting 2’s Comp. OverflowDetecting 2’s Comp. Overflow
TaskTask Given s = TAddw(u , v)
Determine if s = Addw(u , v)
Example
int s, u, v;
s = u + v;
ClaimClaim Overflow iff either:
u, v < 0, s 0 (NegOver)
u, v 0, s < 0 (PosOver)
ovf = (u<0 == v<0) && (u<0 != s<0);
0
2w –1
2w–1PosOver
NegOver
– 44 – COMP 21000, S’15
Characterizing TAddCharacterizing TAddFunctionalityFunctionality
True sum requires w+1 bits
Drop off MSB Treat remaining
bits as 2’s comp. integer
–2w –1
–2w
0
2w –1
2w–1
True Sum
TAdd Result
1 000…0
1 100…0
0 000…0
0 100…0
0 111…1
100…0
000…0
011…1
PosOver
NegOver
(NegOver)
(PosOver)u
v
< 0 > 0
< 0
> 0
NegOver
PosOverTAdd(u , v)
– 45 – COMP 21000, S’15
-8 -6 -4-2 0
24
6
-8
-6
-4
-2
0
2
46
-8
-6
-4
-2
0
2
4
6
8
Visualizing 2’s Comp. AdditionVisualizing 2’s Comp. Addition
ValuesValues 4-bit two’s comp. Range from -8 to +7
Wraps AroundWraps Around If sum 2w–1
Becomes negativeAt most once
If sum < –2w–1
Becomes positiveAt most once
TAdd4(u , v)
u
v
PosOver
NegOver
– 46 – COMP 21000, S’15
How do we get to bits?How do we get to bits?
We write programs in an abstract language like CWe write programs in an abstract language like C
How do we get to the binary representation?How do we get to the binary representation?
Compilers & Assemblers!Compilers & Assemblers!
We writeWe write
x = 5.x = 5.
The compiler changes it intoThe compiler changes it into
mov 5, 0x005Fmov 5, 0x005F
The assembler changes it into:The assembler changes it into:
80483c7: 8b 45 5F 80483c7: 8b 45 5F
Compiler figures out that this is an integer and changes it into 2’s Complement
– 47 – COMP 21000, S’15
Conversions: see slide 17
C Puzzle AnswersC Puzzle Answers Assume machine with 32 bit word size, two’s comp. integers TMin makes a good counterexample in many cases
x < 0 ((x*2) < 0) False: TMin
ux >= 0 True: 0 = UMin
x & 7 == 7 (x<<30) < 0 True: x1 = 1
ux > -1 False: 0
x > y -x < -y False: -1, TMin
x * x >= 0 False: 30426
x > 0 && y > 0 x + y > 0 False: TMax, TMax
x >= 0 -x <= 0 True: –TMax < 0
x <= 0 -x >= 0 False: TMin
x < 0 ((x*2) < 0)
ux >= 0
x & 7 == 7 (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
Casting: see slide 20, 21 When to use unsigned: see slide 26