WEEK 4 ET2640 Logic and Numerical Methods 1ET2640
2 Tokens in C String Literals –A sequence of characters enclosed in double quotes as “…”. For example “13” is a string literal and not number 13. ‘a’ and “a” are different. Operators –Arithmetic operators like +, -, *, /,% etc. –Logical operators like ||, &&, ! etc. and so on. White Spaces –Spaces, new lines, tabs, comments ( A sequence of characters enclosed in /* and */ ) etc. These are used to separate the adjacent identifiers, kewords and constants.
ET26403 Basic Data Types Integral Types –Integers are stored in various sizes. They can be signed or unsigned. –Example Suppose an integer is represented by a byte (8 bits). Leftmost bit is sign bit. If the sign bit is 0, the number is treated as positive. Bit pattern = 75 (decimal). The largest positive number is = 2 7 – 1 = 127. Negative numbers are stored as two’s complement or as one’s complement. -75 = (one’s complement). -75 = (two’s complement).
ET26404 Basic Data Types Integral Types – char Stored as 8 bits. Unsigned 0 to 255. Signed -128 to 127. – short int Stored as 16 bits. Unsigned 0 to Signed to – int Same as either short or long int. – long int Stored as 32 bits. Unsigned 0 to Signed to
ET26405 Basic Data Types Floating Point Numbers –Floating point numbers are rational numbers. Always signed numbers. –float Approximate precision of 6 decimal digits. Typically stored in 4 bytes with 24 bits of signed mantissa and 8 bits of signed exponent. –double Approximate precision of 14 decimal digits. Typically stored in 8 bytes with 56 bits of signed mantissa and 8 bits of signed exponent. –One should check the file limits.h to what is implemented on a particular machine.
ET Constants Numerical Constants –Constants like 12, 253 are stored as int type. No decimal point. –12L or 12l are stored as long int. –12U or 12u are stored as unsigned int. –12UL or 12ul are stored as unsigned long int. –Numbers with a decimal point (12.34) are stored as double. –Numbers with exponent (12e-3 = 12 x ) are stored as double. –12.34f or 1.234e1f are stored as float. –These are not valid constants: 25,0007.1e 4$2002.3e-3.4 etc.
ET26407 Constants Character and string constants –‘c’, a single character in single quotes are stored as char. Some special character are represented as two characters in single quotes. ‘\n’ = newline, ‘\t’ = tab, ‘\\’ = backlash, ‘\”’ = double quotes. Char constants also can be written in terms of their ASCII code. ‘\060’ = ‘0’ (Decimal code is 48). –A sequence of characters enclosed in double quotes is called a string constant or string literal. For example “Charu” “A” “3/9” “x = 5”
ET26408 Variables Naming a Variable –Must be a valid identifier. –Must not be a keyword –Names are case sensitive. –Variables are identified by only first 32 characters. –Library commonly uses names beginning with _. –Naming Styles: Uppercase style and Underscore style –lowerLimitlower_limit –incomeTaxincome_tax
ET Declarations Declaring a Variable –Each variable used must be declared. –A form of a declaration statement is data-type var1, var2,…; –Declaration announces the data type of a variable and allocates appropriate memory location. No initial value (like 0 for integers) should be assumed. –It is possible to assign an initial value to a variable in the declaration itself. data-type var = expression; –Examples int sum = 0; char newLine = ‘\n’; float epsilon = 1.0e-6;
ET Global and Local Variables Global Variables –These variables are declared outside all functions. –Life time of a global variable is the entire execution period of the program. –Can be accessed by any function defined below the declaration, in a file. /* Compute Area and Perimeter of a circle */ #include float pi = ; /* Global */ main() { floatrad;/* Local */ printf( “Enter the radius “ ); scanf(“%f”, &rad); if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad; printf( “Area = %f\n”, area ); printf( “Peri = %f\n”, peri ); } else printf( “Negative radius\n”); printf( “Area = %f\n”, area ); } /* Compute Area and Perimeter of a circle */ #include float pi = ; /* Global */ main() { floatrad;/* Local */ printf( “Enter the radius “ ); scanf(“%f”, &rad); if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad; printf( “Area = %f\n”, area ); printf( “Peri = %f\n”, peri ); } else printf( “Negative radius\n”); printf( “Area = %f\n”, area ); }
ET Global and Local Variables Local Variables –These variables are declared inside some functions. –Life time of a local variable is the entire execution period of the function in which it is defined. –Cannot be accessed by any other function. –In general variables declared inside a block are accessible only in that block. /* Compute Area and Perimeter of a circle */ #include float pi = ; /* Global */ main() { floatrad;/* Local */ printf( “Enter the radius “ ); scanf(“%f”, &rad); if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad; printf( “Area = %f\n”, area ); printf( “Peri = %f\n”, peri ); } else printf( “Negative radius\n”); printf( “Area = %f\n”, area );} /* Compute Area and Perimeter of a circle */ #include float pi = ; /* Global */ main() { floatrad;/* Local */ printf( “Enter the radius “ ); scanf(“%f”, &rad); if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad; printf( “Area = %f\n”, area ); printf( “Peri = %f\n”, peri ); } else printf( “Negative radius\n”); printf( “Area = %f\n”, area );}
PRECEDENCDE OF OPERATORS ET OPERATORDESCRIPTIONASSOCATIVITYRANK ( )Function callLeft-to-right1 [ ]Array Element CallLeft-to-right1 +PlusRight-to-left2 -MinusRight-to-left2 ++IncrementRight-to-left2 --DecrementRight-to-left2 !Logical negationRight-to-left2 -Ones ComplimentRight-to-left2 *Pointer reference(indirection) Right-to-left2 &AddressRight-to-left2 SizeofSize of objectRight-to-left2 (type)Type cast conversionRight-to-left2 *MultiplicationLeft-to-right3 /DivisionLeft-to-right3 %ModulusLeft-to-right3 +AdditionLeft-to-right4 -SubtractionLeft-to-right4
Precedence and Order of Operations ET Operat or Descriptions <<Shift Left >>Shift Right <Less than <=Less than or equal to >Greater than >=Great than or equal to ==Equality !=Not equality &Bitwise AND *Bitwise XOR |Bitwise OR &&Logical AND ||Logical OR ?:Conditional Expression
ET Operators Arit hmetic Operators –+, -, *, / and the modulus operator %. –+ and – have the same precedence and associate left to right. 3 – = ( 3 – 5 ) + 7 3 – ( ) – = ( ( ) – 5 ) + 2 –*, /, % have the same precedence and associate left to right. –The +, - group has lower precendence than the *, / % group. 3 – 5 * 7 / / 2 3 – 35 / / 2 3 – / 2 3 –
ET Operators Arithmetic Operators –% is a modulus operator. x % y results in the remainder when x is divided by y and is zero when x is divisible by y. –Cannot be applied to float or double variables. –Example if ( num % 2 == 0 ) printf(“%d is an even number\n”, num)’; else printf(“%d is an odd number\n”, num);
ET Type Conversions –The operands of a binary operator must have a the same type and the result is also of the same type. – Integer division: c = (9 / 5)*(f - 32) The operands of the division are both int and hence the result also would be int. For correct results, one may write c = (9.0 / 5.0)*(f - 32) –In case the two operands of a binary operator are different, but compatible, then they are converted to the same type by the compiler. The mechanism (set of rules) is called Automatic Type Casting. c = (9.0 / 5)*(f - 32) –It is possible to force a conversion of an operand. This is called Explicit Type casting. c = ((float) 9 / 5)*(f - 32)
ET Automatic Type Casting 1.char and short operands are converted to int 2.Lower data types are converted to the higher data types and result is of higher type. 3.The conversions between unsigned and signed types may not yield intuitive results. 4.Example float f; double d; long l; int i; short s; d + f f will be converted to double i / s s will be converted to int l / i i is converted to long ; long result Hierarchy Double float long Int Short and char
ET Explicit Type Casting –The general form of a type casting operator is –(type-name) expression –It is generally a good practice to use explicit casts than to rely on automatic type conversions. –Example C = (float)9 / 5 * ( f – 32 ) –float to int conversion causes truncation of fractional part –double to float conversion causes rounding of digits –long int to int causes dropping of the higher order bits.
19 Binary Arithmetic Binary addition Binary subtraction Binary multiplication Binary division ET2640
20 Complements of Binary Numbers 1’s complements 2’s complements ET2640
21 Complements of Binary Numbers 1’s complement Change all 1s to 0s and all 0s to 1s ET2640
22 Complements of Binary Numbers 2’s complement Find 1’s complement and then add Input bits Adder Output bits (sum) Carry In (add 1) ’s complement 1’s complement ET2640
23 Signed Numbers ET2640
24 Topics for Signed Numbers Signed-magnitude form 1’s and 2’s complement form Decimal value of signed numbers (How to convert) Range of values (max and min) Floating-point numbers ET2640
25 Signed Numbers Signed-magnitude form –The sign bit is the left-most bit in a signed binary number –A 0 sign bit indicates a positive magnitude –A 1 sign bit indicates a negative magnitude ET2640
26 Signed Numbers 1’s complement form –A negative value is the 1’s complement of the corresponding positive value 2’s complement form –A negative value is the 2’s complement of the corresponding positive value ET2640
27 Signed Numbers Decimal value of signed numbers –Sign-magnitude –1’s complement –2’s complement ET2640
28 Signed Numbers Range of Values Total combinations = 2 n 2’s complement form: – (2 n – 1 ) to + (2 n – 1 – 1) Range for 8 bit number: n = 8 -(2 8-1 ) = -2 7 = -128 minimum +(2 8-1 ) – 1 = = +127 maximum Total combination of numbers is 2 8 = 256. ET2640
29 Signed Numbers Range for 16 bit number: n = 16 -( ) = = minimum +( ) - 1 = = maximum Total combinations is 2 16 = (64K) 8 bit examples: = = = =+127 ET2640
30 Signed Numbers Floating-point numbers –Can represent very large or very small numbers based on scientific notation. Binary point “floats”. Two Parts –Mantissa represents magnitude of number –Exponent represents number of places that binary point is to be moved Three forms –Single-precision (32 bits)float –Double-precision (64 bits)double –Extended-precision (80 bits)long double –Also have Quadruple and Quadruple extended! ET2640
31 Single Precision IEEE 754 standard –Mantissa (F) has hidden bit so actually has 24 bits. Gives 7 significant figures. 1 st bit in mantissa is always a one –Exponent (E) is biased by 127 called Excess-127 Notation Add 127 to exponent so easier to compare Range of exponents is -126 to +128 –Sign (S) bit tells whether number is negative or positive S Exponent (E)Mantissa (fraction, F) 32 bits 1 bit 8 bits 23 bits ET2640
32 Single Precision Example: Convert to Floating Point 1 st, convert to binary using divide by 2 method = Positive number, so sign bit (S) equals 0. 2 nd, count number of places to move binary point = x 2 12 Add 127 to 12 = = Mantissa is fractional part, Finally, put everything together S E F Fill in with trailing zeroes ET2640
33 Special Cases Zero and infinity are special cases –Can have +0 or -0 depending on sign bit –Can also have + ∞ or - ∞ Not a Number (NaN) –if underflow or overflow TypeExponentMantissa Zeroes00 Denormalized numbers0non zero Normalized numbers1 to 2 e − 2any Infinities2 e − 10 NaNs2 e − 1non zero ET2640
34 Examples TypeExponentMantissaValue Zero One Denormalized number × Large normalized number ×10 38 Small normalized number × Infinity Infinity NaN NaN ET2640
35 Double Precision Exponent has 11 bits so uses Excess-1023 Notation Mantissa has 53 bits (one hidden) 53 bits gives 16 significant figures ET2640
36 Arithmetic Operations with Signed Numbers Addition Subtraction Multiplication Division ET2640
37 Arithmetic Operations with Signed Numbers Addition of Signed Numbers The parts of an addition function are: –Augend - The first number –Addend - The second number –Sum - The result Numbers are always added two at a time. ET2640
38 Arithmetic Operations with Signed Numbers Four conditions for adding numbers: 1. Both numbers are positive. 2. A positive number that is larger than a negative number. 3. A negative number that is larger than a positive number. 4. Both numbers are negative. ET2640
39 Arithmetic Operations with Signed Numbers Signs for Addition When both numbers are positive, the sum is positive. When the larger number is positive and the smaller is negative, the sum is positive. The carry is discarded. ET2640
40 Arithmetic Operations with Signed Numbers Signs for Addition When the larger number is negative and the smaller is positive, the sum is negative (2’s complement form). When both numbers are negative, the sum is negative (2’s complement form). The carry bit is discarded. ET2640
41 Examples (8 bit numbers) Add 7 and 4 (both positive) Add 15 and -6 (positive > negative) Add 16 and -24 (negative > positive) Add -5 and -9 (both negative) Discard carry Sign bit is negative so negative number in 2’s complement form Discard carry ET2640
42 Overflow Overflow occurs when number of bits in sum exceeds number of bits in addend or augend. Overflow is indicated by the wrong sign. Occurs only when both numbers are positive or both numbers are negative _________ ____ Sign Incorrect Magnitude Incorrect ET2640
43 Arithmetic Operations with Signed Numbers Subtraction of Signed Numbers The parts of a subtraction function are: –Minuend- The first number –Subtrahend- The second number –Difference- The result Subtraction is addition with the sign of the subtrahend changed. ET2640
44 Arithmetic Operations with Signed Numbers Subtraction The sign of a positive or negative binary number is changed by taking its 2’s complement To subtract two signed numbers, take the 2’s complement of the subtrahend and add. Discard any final carry bit. ET2640
45 Subtraction Examples Find 8 minus 3. Find 12 minus -9. Find -25 minus 19. Find -120 minus Discard carry Minuend Subtrahend Difference Discard carry ET2640
46 Arithmetic Operations with Signed Numbers Multiplication of Signed Numbers The parts of a multiplication function are: –Multiplicand- First number –Multiplier- Second number –Product- Result Multiplication is equivalent to adding a number to itself a number of times equal to the multiplier. ET2640
47 Arithmetic Operations with Signed Numbers There are two methods for multiplication: Direct addition –add multiplicand multiple times equal to the multiplier –Can take a long time if multiplier is large Partial products –Similar to long hand multiplication The method of partial products is the most commonly used. ET2640
48 Arithmetic Operations with Signed Numbers Multiplication of Signed Numbers If the signs are the same, the product is positive. (+ X + = + or - X - = +) If the signs are different, the product is negative. (+ X - = - or - X + = -) ET2640
49 Multiplication Example Both numbers must be in uncomplemented form Multiply 3 by -5. Opposite signs, so product will be negative = = ’s complement of Multiplicand X Multiplier First partial product Second partial product Sum of 1 st and 2 nd Third partial product Sum and Final Product Final result is negative, so take 2’s complement is the result which in decimal is -15. ET2640
50 Arithmetic Operations with Signed Numbers Division of Signed Numbers The parts of a division operation are: –Dividend –Divisor –Quotient Division is equivalent to subtracting the divisor from the dividend a number of times equal to the quotient. ET2640
51 Arithmetic Operations with Signed Numbers Division of Signed Numbers If the signs are the same, the quotient is positive. (+ ÷ + = + or - ÷ - = +) If the signs are different, the quotient is negative. (+ ÷ - = - or - ÷ + = - ) ET2640
52 Division Example Both numbers must be in uncomplemented form Divide by Both numbers are positive so quotient will be positive. Set the quotient to zero initially Dividend ’s complement of Divisor First partial remainder Add 1 to quotient: = quotient: Subtract the divisor from the dividend by using 2’s complement addition. ( ) Ignore the carry bit First partial remainder ’s complement of Divisor zero remainder Add 1 to quotient: = Subtract the divisor from the 1 st partial remainder using 2’s complement addition. So final quotient is and final remainder is ET2640
Logical, Shift and Rotate Operations A particular bit, or set of bits, within the byte can be set to 1 or 0, depending on conditions encountered during the execution of a program. When so used, these bits are often called "flags". Frequently, the programmer must manipulate these individual bits - an activity sometimes known as "bit twiddling". The logical, shift, and rotate operations provide the means for manipulating the bits. ET264053
Logical OR Rules OR Operations OR Results in 1 if either or both of the operands are 1. OR Table 0 OR 0 = 0 0 OR 1 = 1 1 OR 0 = 1 1 OR 1 = 1 ET264054
Logical OR Operation To perform the OR operation, take one column at a time and perform the OR operation using the OR table. Ex 1: OR ET264055
Logical OR Examples Ex 3: OR Ex 2: OR ET264056
Logical XOR Rules XOR Operations The exclusive OR. Similar to OR except that it now gives 0 when both its operands are 1. Rules. 0 XOR 0 = 0 0 XOR 1 = 1 1 XOR 0 = 1 1 XOR 1 = 0 ET
Logical XOR Examples Ex 1: XOR Ex 2: XOR ET264058
Logical AND Rules AND Operations AND yields 1 only if both its operands are 1. Rules. 0 AND 0 = 0 0 AND 1 = 0 1 AND 0 = 0 1 AND 1 = 1 ET264059
Logical AND Examples Ex 1: AND Ex 2: AND ET264060
Logical NOT NOT Operations NOT is a separate operator for flipping the bits. Rules. NOT 0 = 1 NOT 1 = 0 Example.NOT = ET264061
Shift and Rotate operations Whereas logical operations allow the changing of bit values in place, SHIFT and ROTATE operations allow bits to be moved left or right without changing their values. ET264062
Shift Left operation SHL SHL (shift left) shifts each bit one place to the left. The original leftmost bit is lost and a 0 is shifted into the rightmost position. Ex 1.SHL Ex 2.SHL = = ET264063
Shift Left - Multiple Bits SHL # bits means to shift left # times Ex 1: SHL Ex 2: SHL = = ET264064
Shift Right operation SHR SHR (shift right) shifts each bit one place to the right. The original rightmost bit is lost and a 0 is shifted into the leftmost position. Ex 1.SHR Ex 2.SHR = = ET264065
Shift Right – Multiple Bits SHR # bits means to shift right # times Ex 1: SHR = Ex 2: SHR = ET264066
Arithmetic Shift Right operation ASR (retains rightmost sign bit) Shifts each bit one place to the right. The original rightmost bit is lost and a the value of the most significant bit (leftmost bit) is shifted into the new leftmost position. Ex 1.ASR Ex 2.ASR = = ET264067
Arithmetic Shift Right – Multiple Bits ASR # bits means to arithmetic shift right # times Ex 1: ASR = Ex 2: ASR = ET264068
Rotate Left operation ROL ROL (rotate left) shifts each bit one place to the left. The original leftmost bit is shifted into the rightmost position. No bits are lost. Ex 1.ROL Ex 2. ROL = ET264069
Rotate Left – Multiple Bits ROL # bits means to rotate left # times Ex 1: ROL = Ex 2: ROL = ET264070
Rotate Right operation ROR ROR (rotate right) shifts each bit one place to the right. The original rightmost bit is shifted into the leftmost position. No bits are lost. Ex 1.ROR Ex 2.ROR = ET264071
Rotate Right – Multiple Bits ROR # bits means to rotate right # times Ex 1: ROR = Ex 2: ROR = ET264072
73 Hexadecimal Numbers ET2640
74 Hexadecimal Numbers Decimal, binary, and hexadecimal numbers 4 bits is a nibble FF 16 = ET2640
75 Hexadecimal Numbers Binary-to-hexadecimal conversion Hexadecimal-to-decimal conversion Decimal-to-hexadecimal conversion ET2640
76 Hexadecimal Numbers Binary-to-hexadecimal conversion 1.Break the binary number into 4-bit groups 2.Replace each group with the hexadecimal equivalent Convert to Hex C A 5 7 = CA57 16 Convert 10A4 16 to binary = ET2640
77 Hexadecimal Numbers Hexadecimal-to-decimal conversion 1.Convert the hexadecimal to groups of 4-bit binary 2.Convert the binary to decimal ET2640