CSU Banner

CS 163/164, Fall 2016

Lab 12 - Binary Representation

Wed-Fri, Oct. 12-14, 2016


Objectives of this Lab

  1. Introduce you to binary representation,
  2. practice converting decimal numbers to and from binary, and
  3. learn about the bitwise operators, which allow you to manipulate bits in a binary number.

Introduction

Your TA will introduce binary number basics:


Number Conversion

Practice binary to decimal conversion here.

Practice decimal to binary conversion here.

Binary Numbers in Java

The later versions of Java include the ability to specify literal integers in your programs as binary numbers by using the 0b prefix. You can also print the binary values of decimal numbers using Integer.toBinaryString(number), which returns a string. Create an R12 project with the class Binary for the following practice, and follow the instructions below:

Bitwise Operators in Java

The bitwise operators perform AND, OR, and NOT functions that are similar to the logical operators && ||, and !. However, the bitwise operators perform logical functions on every bit of the two operands. The bitwise operators can be used to set, clear, and mask bits in a binary value. For example, assuming 8-bit values:
  0b10010110      0b11001100    
& 0b11100101    | 0b00000010    ~ 0b01100101
  ==========      ==========      ==========
  0b10000100      0b11001110      0b10011010
Now follow the instructions below:

Shift Operators in Java

The shift operators in Jave move bits left or right in the binary word. Some bits may be shifted off and therefore lost. When additional bits are needed, zero bits are added. For example:
0b00001010 << 4 = 0b10100000
0b11010111 >> 4 = 0b00001101
Now follow the instructions below: NOTE: All of the binary numbers shown above are defined as 8-bit numbers, why do we sometimes see more digits? Why do we see fewer digits?

Bonus Problem

Here's a problem that is almost identical to the image transform called swap in the P8 assignment: Write a method called swap that takes a 32-bit binary value as a parameter and swaps the top and bottom 8 bits, for example:
swap(0b10101010 11111111 11111111 00000000) = 0b00000000 11111111 11111111 10101010
The cookbook for this is as follows:
  1. Extract the top 8 bits from the parameter using the bitwise & and a mask, and store the result in an integer called upperBits.
  2. Extract the bottom 8 bits from the parameter using the bitwise & and a mask, and store the result in an integer called lowerBits.
  3. Clear the bottom and top 8 bits from the parameter using the bitwise & operator, and store the result in an integer called middleBits.
  4. Combine upperBits, lowerBits, and middleBits into the result, using the bitwise |, and return the result.
  5. Write a test program for the method that prints the value sent to the method, and the value returned, in binary.

This lab is attendance based, please make sure the TA checks you off on the roster.


CS Banner
CS Building