CS 253. January 14, 2017

Similar documents
Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Goals for this Week. CSC 2400: Computer Systems. Bits, Bytes and Data Types. Binary number system. Finite representations of binary integers

JAVA OPERATORS GENERAL

LAB A Translating Data to Binary

Arithmetic Operations

CSCI 2212: Intermediate Programming / C Chapter 15

Bits, Words, and Integers

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

Chapter 3: Operators, Expressions and Type Conversion

Chapter 4. Operations on Data

2.1. Unit 2. Integer Operations (Arithmetic, Overflow, Bitwise Logic, Shifting)

Arithmetic and Bitwise Operations on Binary Data

Topic Notes: Bits and Bytes and Numbers

Lecture 13 Bit Operations

Binary representation of integer numbers Operations on bits

4 Operations On Data 4.1. Foundations of Computer Science Cengage Learning

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

CS 33. Data Representation, Part 1. CS33 Intro to Computer Systems VII 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Arithmetic and Bitwise Operations on Binary Data

CS 241 Data Organization Binary

CS2630: Computer Organization Homework 1 Bits, bytes, and memory organization Due January 25, 2017, 11:59pm

Topic Notes: Bits and Bytes and Numbers

Introduction to Computing Systems Fall Lab # 3

AGENDA Binary Operations CS 3330 Samira Khan

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

Computer Science 324 Computer Architecture Mount Holyoke College Fall Topic Notes: Bits and Bytes and Numbers

BITWISE OPERATORS. There are a number of ways to manipulate binary values. Just as you can with

CS 24: INTRODUCTION TO. Spring 2015 Lecture 2 COMPUTING SYSTEMS

SECTION II: LANGUAGE BASICS

Computer Architecture and System Software Lecture 02: Overview of Computer Systems & Start of Chapter 2

Lecture 17 Bit Operations

Bit Manipulation in C

A flow chart is a graphical or symbolic representation of a process.

2. MACHINE REPRESENTATION OF TYPICAL ARITHMETIC DATA FORMATS (NATURAL AND INTEGER NUMBERS).

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

The Design of C: A Rational Reconstruction"

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

Appendix. Bit Operators

CS 31: Intro to Systems Binary Arithmetic. Kevin Webb Swarthmore College January 26, 2016

Operators. Java operators are classified into three categories:

Bitwise Operator and Typecasting

But first, encode deck of cards. Integer Representation. Two possible representations. Two better representations WELLESLEY CS 240 9/8/15

Computer Systems C S Cynthia Lee

COMP2611: Computer Organization. Data Representation

ENE 334 Microprocessors

CSC 2400: Computer Systems. Bit- Level vs. Logical Opera<ons. Bit- Level Operators. Common to C and Java &,, ~, ^, <<, >>

C-string format with scanf/printf

Assembly Language for Intel-Based Computers, 4 th Edition. Chapter 1: Basic Concepts. Chapter Overview. Welcome to Assembly Language

CS 31: Introduction to Computer Systems. 03: Binary Arithmetic January 29

The Design of C: A Rational Reconstruction

Binary Values. CSE 410 Lecture 02

Applied Computer Programming

4/8/17. Admin. Assignment 5 BINARY. David Kauchak CS 52 Spring 2017

Data III & Integers I

Bitwise Data Manipulation. Bitwise operations More on integers

Logical and Bitwise Expressions

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

The Design of C: A Rational Reconstruction" Jennifer Rexford!

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

BITS, BYTES, AND INTEGERS

SIMPLE PROGRAMMING. The 10 Minute Guide to Bitwise Operators

Math in MIPS. Subtracting a binary number from another binary number also bears an uncanny resemblance to the way it s done in decimal.

The Design of C: A Rational Reconstruction

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

Logic, Words, and Integers

Bitwise Instructions

CSE 303 Lecture 18. Bitwise operations. reading: Programming in C Ch. 12. slides created by Marty Stepp

Assignment 3: Binary numbers, data types and C Programs Due 11:59pm Monday 26th March 2018

CS Bootcamp Boolean Logic Autumn 2015 A B A B T T T T F F F T F F F F T T T T F T F T T F F F

CSE 351: The Hardware/Software Interface. Section 2 Integer representations, two s complement, and bitwise operators

CS 107 Lecture 2: Bits and Bytes (continued)

CSCI2467: Systems Programming Concepts

The type of all data used in a C (or C++) program must be specified

Data III & Integers I

Brock Wilcox CS470 Homework Assignment 2

Inf2C - Computer Systems Lecture 2 Data Representation

CS33 Project Gear Up. Data

Floating-Point Data Representation and Manipulation 198:231 Introduction to Computer Organization Lecture 3

Operations On Data CHAPTER 4. (Solutions to Odd-Numbered Problems) Review Questions

BINARY SYSTEM. Binary system is used in digital systems because it is:

The ALU consists of combinational logic. Processes all data in the CPU. ALL von Neuman machines have an ALU loop.

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

ICS Instructor: Aleksandar Kuzmanovic TA: Ionut Trestian Recitation 2

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

A complement number system is used to represent positive and negative integers. A complement number system is based on a fixed length representation

C Language Programming

Binary Arithmetic CS 64: Computer Organization and Design Logic Lecture #2 Fall 2018

COMP MIPS instructions 2 Feb. 8, f = g + h i;

MC1601 Computer Organization

Decimal & Binary Representation Systems. Decimal & Binary Representation Systems

World Inside a Computer is Binary

The type of all data used in a C++ program must be specified

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

Data III & Integers I

Under the Hood: Data Representations, Memory and Bit Operations. Computer Science 104 Lecture 3

Chapter 2. Instruction Set. RISC vs. CISC Instruction set. The University of Adelaide, School of Computer Science 18 September 2017

CT 229. Java Syntax 26/09/2006 CT229

Transcription:

CS 253 Department of Computer Science College of Engineering Boise State University January 14, 2017 1/30

Motivation Most programming tasks can be implemented using abstractions (e.g. representing data as an int, long, char,...) However, some programming tasks require manipulation of data that is not a standard length, so we need to work at the bit level. Some of these tasks include low-level device control, error detection and correction algorithms, data compression, encryption algorithms, and other optimizations. Instead of writing solutions in assembly (tedious and not portable due to specific computer architecture), we use a programming language that provides good abstraction, but still allows for low-level control. 2/30

Note about signed and unsigned integers If the size of an unsigned int, x, is 4 bytes, then it is stored in memory as a 32-bit binary number of the form x base2 = b 31 b 30...b n...b 1 b 0, where b n {0,1} And the decimal value of x is calculated as follows. x base10 = b 31 2 31 + b 30 2 30 +... + b n 2 n +... + b 1 2 1 + b 0 2 0 In the case where x = 277, x may be stored as 00000000000000000000000100010101. Similarly, an 8-bit unsigned char, c would be stored in memory as c base2 = b 7 b 6...b n...b 0, where b n {0,1} The same applies for all unsigned integer types (long, short, etc). 3/30

Note about signed and unsigned integers In a k-bit signed type, the Most Significant Bit (MSB) (b k 1 ), is used as a sign bit (0 = positive, 1 = negative). For example, if x = 10000010 2, then unsigned char x = 2 7 + 2 1 = 128 + 2 = 130 signed char x = (2 7 2 1 ) = (128 2) = -126 Therefore, signed chars range = -128 to 127 and unsigned chars range = 0 to 255. The same logic applies for 32-bit/64-bit ints. 4/30

and Bitshift Two sets of operators are useful: bitwise operators bitshift operators operators allow you to read and manipulate bits in variables of certain types. Available in C, C++, Java, C# 5/30

operators only work on integer types: char, short, int and long Two types of bitwise operators Unary bitwise operators Binary bitwise operators 6/30

Only one unary operator: NOT ( ) (1 s complement) Flips every bit. 1 s become 0 s and 0 s become 1 s. ~x Binary bitwise operators AND (&) Similar to boolean &&, but works on the bit level. x & y OR ( ) Similar to boolean, but works on the bit level. x y XOR (ˆ) (exclusive-or) Only returns a 1 if one bit is a 1 and the other is 0. Unlike OR, XOR returns 0 if both bits are 1. x ^ y 7/30

Examples and exercises Example: C-examples/bitwise-operators/simple.c Run with GDB. Print binary values using print \t x. Exercise: Define XOR in terms of NOT, AND and OR. 8/30

What can we do with bitwise operators? You can represent 32 boolean variables very compactly. You can use an int variable (assuming it has 4 bytes) as a 32 bit Boolean array. Unlike the bool type in C++, which presumably requires one byte, you can make your own Boolean variable using a single bit. However, to do so, you need to access individual bits. 9/30

What can we do with bitwise operators? (contd.) When reading input from a device - Each bit may indicate a status for the device or it may be one bit of control for that device. Bit manipulation is considered really low-level programming. Many higher level languages hide the operations from the programmer However, languages like C are often used for systems programming where data representation is quite important. 10/30

What can we do with bitwise operators? (contd.) Setting, un-setting, or checking whether a specific bit, i, is set. Ideas? Masks If you need to check whether a specific bit is set, then you need to create an appropriate mask and use bitwise operators. For e.g., #define MSB_MASK 0x80 // 1000 0000 unsigned char x = 77; // 0111 0111 How would we set MSB? x = x mask 11/30

Exercise Exercise: Assume we have a device with the following status fields. Each status will be stored as a bit of an unsigned char (8 bits). ENABLE READY ERROR RUNNING LOADED LOCKED (null) (null) b 7 b 6 b 5 b 4 b 3 b 2 b 1 b 0 Create a bit mask for each of the status bits. How would you ENABLE the device and set it to READY? How would you indicate an error? (if there is an error, then it won t be ready anymore) How would you clear all bits? 12/30

Bitshift The << and >> operators have different meanings in C and C++ In C, they are bitshift operators In C++, they are stream insertion and extraction operators The bitshift operators take two arguments x << n x >> n x can be any kind of int variable or char variable and n can be any kind of int variable 13/30

Left shift operator Left shift operator << x << n shifts the bits for x leftward by n bits, filling the vacated bits by zeroes Eg : x = 50 = 0011 0010 followed by x<<4 Think about what shifting left means? Left shifting by k bits = multiplying by 2 k Each bit contributes 2 i to the overall value of the number 14/30

Issues with «Operator For unsigned int, when the first "1" falls off the left edge, the operation has overflowed. It means that you have multiplied by 2 k such that the result is larger than the largest possible unsigned int. Shifting left on signed values also works, but overflow occurs when the most significant bit changes values (from 0 to 1, or 1 to 0). 15/30

Right shift operator Right shift operator >> x >> n shifts the bit rightward by n bits Example: x = 1011 0010 and x>>4 What does shifting right mean? For unsigned int, and sometimes for signed int, shifting right by k bits is equivalent to dividing by 2 k (using integer division). 16/30

Issues with» Operator Creates few problems regardless of data type Shifting does NOT change values x = 3 ; n = 2 ; x << n ; printf("%d", x); // Prints 3 NOT 12 Shifting right using >> for signed numbers is implementation dependent. It may shift in the sign bit from the left, or it may shift in 0 s (it makes more sense to keep shifting in the sign bit). 17/30

Example Add bitshift operators to C-examples/bitwise-operators/simple.c Run with GDB. 18/30

Creating a Dynamic Mask Recall: If you need to check whether a specific bit is set, then you need to create an appropriate mask and use bitwise operators. For e.g., unsigned char mask = 128; // 1000 0000 unsigned char x = 77; // 0111 0111 But how would you create dynamic bit mask? unsigned char mask = 1 << i; Causes i th bit to be set to 1. If i = 4, then the mask would be 00010000. 19/30

Checking if a bit is set Create a mask. Followed by using a bitwise AND operator unsigned char isbitset( unsigned char ch, int i ) { unsigned char mask = 1U << i; return mask & ch; } If return value is anything other than 0, then bit i was set. 20/30

Setting a bit Create a mask Followed by using a bitwise OR operator unsigned char setbit( unsigned char ch, int i ) { unsigned char mask = 1U << i; return mask ch; } 21/30

exercise Write a function that clears bit i. (i.e., makes bit i s value 0 no matter what). unsigned char clearbit(unsigned char ch, int i) { } 22/30

Is Any Bit Set Within a Range (1) Is any bit set within a range? bool isbitsetinrange(unsigned char ch, int low, int high ); This function returns true if any bit within b high...b low has a value of 1. Assume that low <= high. All bits could be 1, or some bits could be 1, or exactly 1 bit in the range could be 1, and they would all return true. Return false only when all the bits in that range are 0. 23/30

Is Any Bit Set Within a Range (2) How do we check for a bit set within a range? Method 1: Write a for loop that checks if bit i is set for (int i = low; i <= high; i++) { if (isbitset(ch, i) return true; } return false; 24/30

Is Any Bit Set Within a Range (3) Method 2: No loops. Define a mask over the specified range. Combination of bitwise operation and subtraction. Need a mask with 1 s between b low and b high. How can you get k 1 s? One method: unsigned char mask = 1 << k; // if k = 3, 00001000 mask = mask - 1; // 00000111 Think about it... 25/30

Is Any Bit Set Within a Range (4) How do we use this to get get mask for range from b low to b high? Method 1: int k = (high - low) + 1; // e.g. high = 4, low = 2, k = 3 unsigned char mask = 1 << k; // 00001000 mask = mask - 1; // 00000111 mask = mask << low; // 00011100 Method 2: unsigned char maskhigh = (1 << (high + 1)) - 1; // 00011111 unsigned char masklow = (1 << low) - 1; // 00000011 unsigned char mask = maskhigh ^ masklow; // 00011100 26/30

Is Any Bit Set Within a Range (5) Function now looks like bool isbitsetinrange(unsigned char ch, int low, int high) { unsigned char maskhigh = (1 << (high + 1)) - 1; unsigned char masklow = (1 << low) - 1; unsigned char mask = maskhigh ^ masklow; // 00011100 return ch & mask; } As long as at least one bit is 1, then the result is non-zero, and thus, the return value is true. 27/30

Another example Write a function getbits(x, p, n) that returns the (right adjusted) n-bit field of x that begins at position p. Assume that bit position 0 is at the right end and that n and p are sensible positive values. unsigned int getbits (unsigned int x, int p, int n) { return (x >> (p+1-n)) & ~(~0 << n); } See example C-examples/bitwise-operators/getbits.c. 28/30

References The C Programming Language Kernighan and Ritchie Computer Organization & Design: The Hardware/Software Interface, David Patterson & John Hennessy, Morgan Kaufmann http://www.cs.umd.edu/class/spring2003/cmsc311/ Notes/index.html 29/30

Exercises Read Section 2.9 from the C book. Write a function that computes the parity bit for a given unsigned integer. The parity bit is 1 if the number of 1 bits in the integer is even. The parity bit is 0 if the number of 1 bits in the integer is odd. This is known as odd-parity. We can also compute the even-parity, which is the opposite of odd-parity. Parity bits are used for error detection in data transmission. Write a function that sets bit from b high...b low to all 1 s, while leaving the remaining bits unchanged. Write a function that clears bits from b high...b low to all 0 s, while leaving the remaining bits unchanged. 30/30