# binary numbers

Post on 21-Jan-2016

41 views

Category:

## Documents

Embed Size (px)

DESCRIPTION

Binary Numbers. COS 217. Goals of Today’s Lecture. Binary numbers Why binary? Converting base 10 to base 2 Octal and hexadecimal Integers Unsigned integers Integer addition Signed integers C bit operators And, or, not, and xor Shift-left and shift-right - PowerPoint PPT Presentation

TRANSCRIPT

• Binary NumbersCOS 217

• Goals of Todays LectureBinary numbersWhy binary?Converting base 10 to base 2Octal and hexadecimalIntegersUnsigned integersInteger additionSigned integersC bit operatorsAnd, or, not, and xorShift-left and shift-rightFunction for counting the number of 1 bitsFunction for XOR encryption of a message

• Why Bits (Binary Digits)?Computers are built using digital circuitsInputs and outputs can have only two valuesTrue (high voltage) or false (low voltage)Represented as 1 and 0Can represent many kinds of informationBoolean (true or false)Numbers (23, 79, )Characters (a, z, )PixelsSoundCan manipulate in many waysRead and writeLogical operationsArithmetic

• Base 10 and Base 2Base 10Each digit represents a power of 104173 = 4 x 103 + 1 x 102 + 7 x 101 + 3 x 100Base 2Each bit represents a power of 210110 = 1 x 24 + 0 x 23 + 1 x 22 + 0 x 20 = 22Divide repeatedly by 2 and keep remainders

12/2 = 6 R = 06/2 = 3R = 03/2 = 1R = 11/2 = 0R = 1Result = 1100

• Writing Bits is Tedious for PeopleOctal (base 8)Digits 0, 1, , 7In C: 00, 01, , 07Hexadecimal (base 16)Digits 0, 1, , 9, A, B, C, D, E, FIn C: 0x0, 0x1, , 0xf

Thus the 16-bit binary number

1011 0010 1010 1001

converted to hex is

B2A9

0000 = 01000 = 80001 = 11001 = 90010 = 21010 = A0011 = 31011 = B0100 = 41100 = C0101 = 51101 = D0110 = 61110 = E0111 = 71111 = F

• Representing Colors: RGBThree primary colorsRedGreenBlueStrength8-bit number for each color (e.g., two hex digits)So, 24 bits to specify a colorIn HTML, on the course Web pageRed: Symbol Table Assignment DueBlue: Fall RecessSame thing in digital camerasEach pixel is a mixture of red, green, and blue

• Storing Integers on the ComputerFixed number of bits in memoryShort: usually 16 bitsInt: 16 or 32 bitsLong: 32 bitsUnsigned integerNo sign bitAlways positive or 0All arithmetic is modulo 2nExample of unsigned int00000001 100001111 1500010000 1600100001 3311111111 255

• Adding Two Integers: Base 10From right to left, we add each pair of digitsWe write the sum, and add the carry to the next column198+264SumCarry011+001SumCarry216140010110

• Binary Sums and CarriesabSumabCarry000000011010101100110111XORAND 0100 0101 + 0110 0111 1010 110069103172

• Modulo ArithmeticConsider only numbers in a rangeE.g., five-digit car odometer: 0, 1, , 99999E.g., eight-bit numbers 0, 1, , 255Roll-over when you run out of spaceE.g., car odometer goes from 99999 to 0, 1, E.g., eight-bit number goes from 255 to 0, 1, Adding 2n doesnt change the answerFor eight-bit number, n=8 and 2n=256E.g., (37 + 256) mod 256 is simply 27This can help us do subtractionSuppose you want to compute a bNote that this equals a + (256 -1 - b) + 1

• Ones and Twos ComplementOnes complement: flip every bitE.g., b is 01000101 (i.e., 69 in base 10)Ones complement is 10111010Thats simply 255-69Subtracting from 11111111 is easy (no carry needed!)

Twos complementAdd 1 to the ones complementE.g., (255 69) + 1 1011 1011 - 0100 0101 1111 1111 1011 1010bones complement

• Putting it All TogetherComputing a b for unsigned integersSame as a + 256 bSame as a + (255 b) + 1Same as a + onecomplement(b) + 1Same as a + twocomplement(b)Example: 172 69The original number 69: 0100 0101Ones complement of 69: 1011 1010 Twos complement of 69: 1011 1011Add to the number 172: 1010 1100The sum comes to: 0110 0111Equals: 103 in base 10 1010 1100 + 1011 1011 1 0110 0111

• Signed IntegersSign-magnitude representationUse one bit to store the signZero for positive numberOne for negative numberExamplesE.g., 0010 1100 44E.g., 1010 1100 -44Hard to do arithmetic this way, so it is rarely usedComplement representationOnes complementFlip every bitE.g., 1101 0011 -44Twos complementFlip every bit, then add 1E.g., 1101 0100 -44

• Overflow: Running Out of RoomAdding two large integers togetherSum might be too large to store in the number of bits allowedWhat happens?Unsigned numbersAll arithmetic is modulo arithmeticSum would just wrap aroundSigned integersCan get nonsense valuesExample with 16-bit integers Sum: 10000+20000+30000 Result: -5536In this case, fixable by using long

• Bitwise Operators: AND and ORBitwise AND (&)

Mod on the cheap!E.g., h = 53 & 15;

Bitwise OR (|)001101010000111153& 15000001015

• Bitwise Operators: Not and XOROnes complement (~)Turns 0 to 1, and 1 to 0E.g., set last three bits to 0x = x & ~7;XOR (^)0 if both bits are the same1 if the two bits are different^01010110

• Bitwise Operators: Shift Left/RightShift left (): Divide by powers of 2Shift some # of bits to the rightFor unsigned integer, fill in blanks with 0What about signed integers? Varies across machinesCan vary from one machine to another!001101005311010000532

• Count Number of 1s in an IntegerFunction bitcount(unsigned x)Input: unsigned integerOutput: number of bits set to 1 in the binary representation of xMain ideaIsolate the last bit and see if it is equal to 1Shift to the right by one bit, and repeat

int bitcount(unsigned x) { int b; for (b=0; x!=0; x >>= 1) if (x & 01) b++; return b;}

• XOR EncryptionProgram to encrypt text with a keyInput: original text in stdinOutput: encrypted text in stdoutUse the same program to decrypt text with a keyInput: encrypted text in stdinOutput: original text in stdoutBasic ideaStart with a key, some 8-bit number (e.g., 0110 0111)Do an operation that can be invertedE.g., XOR each character with the 8-bit number

0100 0101 ^ 0110 0111 0010 0010 0010 0010 ^ 0110 0111 0100 0101

• XOR Encryption, ContinuedBut, we have a problemSome characters are control charactersThese characters dont printSo, lets play it safeIf the encrypted character would be a control character just print the original, unencrypted characterNote: the same thing will happen when decrypting, so were okayC function iscntrl()Returns true if the character is a control character

• XOR Encryption, C Code#define KEY &int main() { int orig_char, new_char;

while ((orig_char = getchar()) != EOF) { new_char = orig_char ^ KEY; if (iscntrl(new_char)) putchar(orig_char); else putchar(new_char); } return 0;}

• ConclusionsComputer represents everything in binaryIntegers, floating-point numbers, characters, addresses, Pixels, sounds, colors, etc.Binary arithmetic through logic operationsSum (XOR) and Carry (AND)Twos complement for subtractionBinary operations in CAND, OR, NOT, and XORShift left and shift rightUseful for efficient and concise code, though sometimes cryptic

• Next WeekCanceling second preceptMonday/Tuesday precept as usualCanceling the Wednesday/Thursday precept due to midtermsThursday lecture timeMidterm examOpen book and open notesPractice exams online