Bit Operations Horton pp. 70 - 76. Why we need to work with bits Sometimes one bit is enough to store your data: say the gender of the student (e.g. 0.

Slides:



Advertisements
Similar presentations
Intro to CS – Honors I Representing Numbers GEORGIOS PORTOKALIDIS
Advertisements

©Brooks/Cole, 2003 Chapter 4 Operations on Bits. ©Brooks/Cole, 2003 Apply arithmetic operations on bits when the integer is represented in two’s complement.
Computer Structure - Computer Arithmetic Goal: Representing Numbers in Binary  Base 10 (decimal) - Numbers are represented using 10 numerals: 0, 1, 2,
1 Representing Numbers Using Bases Numbers in base 10 are called decimal numbers, they are composed of 10 numerals ( ספרות ) = 9* * *10.
Assembly Language and Computer Architecture Using C++ and Java
1 Lecture 3 Bit Operations Floating Point – 32 bits or 64 bits 1.

Assembly Language and Computer Architecture Using C++ and Java
24/06/2015CSE1303 Part B lecture notes 1 Words, bits and pieces Lecture B05 Lecture notes section B05.
Computer ArchitectureFall 2008 © August 25, CS 447 – Computer Architecture Lecture 3 Computer Arithmetic (1)
More about Numerical Computation CS-2301, B-Term More about Numerical Computation CS-2301, System Programming for Non-Majors (Slides include materials.
Bit Operations C is well suited to system programming because it contains operators that can manipulate data at the bit level –Example: The Internet requires.
A bit can have one of two values: 0 or 1. The C language provides four operators that can be used to perform bitwise operations on the individual bits.
1 Bitwise Operators. 2 Bits and Constants 3 Bitwise Operators Bitwise "and" operator & Bitwise "or" operator | Bitwise "exclusive or" operator ^ Bitwise.
1 Bitwise Operators. 2 Bitwise Operators (integers) Bitwise "and" operator & Bitwise "or" operator | Bitwise "exclusive or" operator ^ Bitwise "ones complement"
Bitwise Operations CSE 2451 Rong Shi. Working with bits – int values Decimal (not a power of two – used for human readability) – No preceding label –
Binary Arithmetic Math For Computers.
Operations on data CHAPTER 4.
4 Operations On Data Foundations of Computer Science ã Cengage Learning.
+ CS 325: CS Hardware and Software Organization and Architecture Exam 1: Study Guide.
1 CS 162 Introduction to Computer Science Chapter 5 ASCII to Integer Conversion Herbert G. Mayer, PSU Status 11/9/2014.
Numbering systems.
CSCI-365 Computer Organization Lecture Note: Some slides and/or pictures in the following are adapted from: Computer Organization and Design, Patterson.
Computer Arithmetic Nizamettin AYDIN
1 Homework Turn in HW2 tonight HW3 is on-line already Questions?
10-Sep Fall 2001: copyright ©T. Pearce, D. Hutchinson, L. Marshall Sept Representing Information in Computers:  numbers: counting numbers,
Bit Manipulation when every bit counts. Questions on Bit Manipulation l what is the motivation for bit manipulation l what is the binary, hexadecimal,
Bits and Bytes. BITWISE OPERATORS Recall boolean logical operators in Java… boolean logical operators: &, |, ^ not: ! Show truth tables.
1 CS103 Guest Lecture Number Systems & Conversion Bitwise Logic Operations.
Bitwise operators. Representing integers We typically think in terms of decimal (base 10) numbers.  Why?  A decimal (or base 10) number consists of.
Operations on Bits Arithmetic Operations Logic Operations
Lecture12. Outline Binary representation of integer numbers Operations on bits –The Bitwise AND Operator –The Bitwise Inclusive-OR Operator –The Bitwise.
Bitwise operators. Representing integers We typically think in terms of decimal (base 10) numbers.  Why?  A decimal (or base 10) number consists of.
Computer Organization and Assembly Language Bitwise Operators.
Bitwise Operators in C. Bitwise operators are used to manipulate one or more bits from integral operands like char, int, short, long.
Bitwise Operators Fall 2008 Dr. David A. Gaitros
Kavita Bala CS 3410, Spring 2014 Computer Science Cornell University.
1 Logic, Shift, and Rotate Instructions Read Sections 6.2, 7.2 and 7.3 of textbook.
CSE 351 Number Representation & Operators Section 2 October 8, 2015.
D75P 34R - HNC Computer Architecture Week 4 Signed Integers © C Nyssen/Aberdeen College 2004 All images © C Nyssen /Aberdeen College unless otherwise.
Expressions and Operators in C. Expressions and Operators Examples: 3 + 5; x; x=0; x=x+1; printf("%d",x); Two types: – Function calls – The expressions.
Number Representation and Arithmetic Circuits
CSE 351 Number Representation. Number Bases Any numerical value can be represented as a linear combination of powers of n, where n is an integer greater.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Number Systems and Computer Arithmetic Winter 2014 COMP 1380 Discrete Structures I Computing Science Thompson Rivers University.
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Expression and Operator. Expressions and Operators u Examples: 3 + 5; x; x=0; x=x+1; printf("%d",x); u Two types: –Function calls –The expressions formed.
MicroProcessors Lec. 4 Dr. Tamer Samy Gaafar. Course Web Page —
CHAPTER 4 CS 3370 – C++ Expressions. Operators Unary -, *, ++, -- higher precedence than binary operators most associate right-to-left Binary most associate.
Windows Programming Lecture 06. Data Types Classification Data types are classified in two categories that is, – those data types which stores decimal.
CMSC 202 Lesson 26 Miscellaneous Topics. Warmup Decide which of the following are legal statements: int a = 7; const int b = 6; int * const p1 = & a;
CompSci From bits to bytes to ints  At some level everything is stored as either a zero or a one  A bit is a binary digit a byte is a binary.
From bits to bytes to ints
CSE 220 – C Programming Bitwise Operators.
Chapter 4 Operations on Bits.
Instructor: David Ferry
Bit Operations Horton pp
Number Systems and Bitwise Operation
Andy Wang Object Oriented Programming in C++ COP 3330
More about Numerical Computation
Bit-wise and bit-shift operators
Homework Homework Continue Reading K&R Chapter 2 Questions?
Comp Org & Assembly Lang
Bitwise operators.
Module 10 Operations on Bits
靜夜思 床前明月光, 疑是地上霜。 舉頭望明月, 低頭思故鄉。 ~ 李白 李商隱.
Bit Manipulations CS212.
Bit Operations Horton pp
Presentation transcript:

Bit Operations Horton pp

Why we need to work with bits Sometimes one bit is enough to store your data: say the gender of the student (e.g. 0 for men, 1 for women). We don’t have a 1-bit variable type in C++, so for gender, you will have to use a unsigned char or char type variable. But if you need say 8 such 1-bit variables, say to record if the student were present in the times when attendance was taken, then you can actually combine all into one char variable. class student { … private: unsigned char attendance; //now I can fit 8 bits into this, we will see how } In C++, there is special container class, called bitset, that is designed to store bits. But we will not see and use it. And you are not allowed to use it in this course.

Packing bits “Packing” 8 1-bit variables into 1 char variable is easy. Say you know that the student were present in the first 3 class and not in the last 5. The variable attendance can be set as: unsigned char attendance = 7; where the lest significant 3 bits represent the first 3 attendances (just a choice, it could be the other way around as well). But in addition to being able to set a variable’s value, we need to be able to handle each bit separately, for which we need bit operators.

Hexadecimal literals and output In C++ a hexadecimal literal (number) is represented by preceeding 0x before the literal. E.g. 0xb4a2 // equivalent to 11x x x = (decimal) char ch = 0x7c; // ch contains 124 (7x16+ 12) When you want to display a numeric value in hexadecimal, use hex in cout before the value to be displayed. –This affects all future integer outputs to be displayed in hexadecimal, so if you want to switch back to decimal, use dec later. short nums = -200; cout << "hexadecimal: " << hex << nums << " decimal: " << dec << nums << endl; Output: hexadecimal: ff38 decimal: -200 unsigned int numi = 0xfd04e0e4; cout << "hexadecimal: " << hex << numi << " decimal: " << dec << numi << endl; Output: hexadecimal: fd04e0e4 decimal:

Bit Operators & Bitwise and | Bitwise or ^ Bitwise exclusive or ~ Complement (unary operator, takes only one operand) << shift left >> shift right Do not confuse && with & || with |

Bitwise Operations: AND Take the AND of the two numbers, bit by bit x y z char x,y,z; x = 0xd5; y = 0x6c; z = x&y; aba & b

Bitwise AND unsigned char c1, c2, c3; c1 = 0x45; c2 = 0x71; c3 = c1&c2; c1 : c2 : c3 : (=0x41 = 4x16+1 = )

Bitwise OR Take the OR of the two numbers, bit by bit. unsigned char c1, c2, c3; c1 = 0x45; c2 = 0x71; c3 = c1 | c2; c1 : c2 : c3 : (=0x75 = 7x16+5 = ) aba | b

Bitwise XOR Take the Exclusive OR of the two numbers, bit by bit. unsigned char c1, c2, c3; c1 = 0x45; c2 = 0x71; c3 = c1 ^ c2; c1 : c2 : c3 : (=0x34 = 3x16+4 = ) aba ^ b

Bitwise Complement Complement operation (~) converts bits with value 0 to 1 and bits with value 1 to 0. unsigned char b1 = 0xc1; // unsigned char b4 = 0x08; // b4 = ~b1; // a~a 01 10

What do these two statements do? char x = 0xA5; if ( x & 0x08 ) //what does this mean? x = x | 0x02; //what happened to x? These are two of the most important bit operations! We will see more later, but basically you can access a particular bit and you can set a particular bit with these two operations.

Logic Operators versus Bitwise Logic Ops. The operators &&, || and ! are not bitwise logic operators! –The result of !, && and || operations is an integral data type with the value 0 (every bit is a zero) or 1 (Least Significant bit is 1, all the others are 0).

Shift Operators Shift operators move bits left or right, discarding bits from one side and filling the other side with 0s. << means shift left >> means shift right Do not confuse with stream operators how many times it is shifted

Bit operations: left shift Suppose we want to shift the bits of a number N, k bits to the left –denoted N << k drop leftmost k bits append k zeros to the right Ex: y = x << 1; Another example: unsigned char c2 = 0x9C; // c = c2 << 2 // x y

Bit Shifting as Multiplication Shift left by one position means multiplication by 2 (provided that the result is in the range) - Works as multiplication for both unsigned & 2’s complement numbers - May overflow. –What is the effect of shifting a number left by 3? 0011 = = = =

Bit operations: right shift As opposed to left shift, the right shift works differently for signed and unsigned numbers. Suppose we want to shift N by k bits to the right (denoted N >> k): –For unsigned numbers (i.e. unsigned char, unsigned int, etc.): drop rightmost k bits append k zeros to the left –For signed numbers (i.e. char, int, etc.): drop the rightmost k bits append the sign bit k times to the left

right shift operator:examples Signed ( all your variables are signed unless you specify “unsigned” specifically ): –positives: char c = 8; // c = c >> 2 // = 2 10 –negatives: char c = - 8; // in 2s comp. c = c >> 2 // which is –Called arithmetic shift Unsigned: unsigned char d = 0xf8; // ( ) d = d >> 2 // which is –Called logical shift

Bit Shifting as Division: summary 0111 = = = = -4 Always rounds down! CAUTION: Regular division of negative integers rounds down magnitude-wise. E.g. -7/2 is -3 Arithmetic shift right for one bit divides by 2 for signed numbers 0111 = = = = 4 Always rounds down! Logical shift right for one bit divides by 2 for unsigned:

Bit Shifting as Multiplication & Division Why useful? –Simpler, thus faster, than general multiplication & division Can shift multiple positions at once: –Multiplies or divides by corresponding power of 2. –a << 5 (multiply by 2 5 ) –a >> 5 (divide by 2 5 ) Remember, when you need to use only positive numbers or you need to manipulate bits, use unsigned numbers.

Self-Quiz What are the resulting values of x,y and z? char x,y,z; x = 0x33; x = (x << 3) | 0x0F; y = (x >> 1) & 0x0F; z = x && y;

Example for setting, testing, and clearing the bits of bytes const char IO_ERROR = 0x01; //LSB (right-most bit) is 1, others are 0 const char CHANNEL_DOWN = 0x10; char flags = 0; //if ever CHANNEL_DOWN event happens, set its corresponding bit in the flags variable flags = flags | CHANNEL_DOWN; // set the 5th bit... //to check what errors may have happened... if ((flags & IO_ERROR ) != 0) // check the 1st bit cout << "I/O error flag is set"; else if ((flags & CHANNEL_DOWN) != 0) // check the 5th bit cout << "Channel down error flag is set";... flags = flags & ~IO_ERROR; // clear the ERROR flag This is also called masking

22 Example 2: Attendance unsigned char attendance = 0x00; //let the LSB be for quiz 1, the next one is for quiz 2,... //0 means unattended, 1 means attended //there are total of 8 quizzes; initally all unattended unsigned char mask=0x01; //Draft code showing how attendance array may be filled //if attended to quiz 1 attendance = attendance | mask; //if attended quiz 3 mask = mask << 2; // mask becomes attendance = attendance | mask;... //to display attendance information mask=0x01; for (int i=1; i <= 8; i++) { if (attendance & mask) cout << "Student attended quiz number " << i << endl; else cout << "Student missed quiz number " << i << endl; mask = mask << 1; }