26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 20 <strong>Java</strong> Utilities Package and Bit Manipulation 1185<br />

Bit 1 Bit 2 Bit 1 ^ Bit 2<br />

0 0 0<br />

1 0 1<br />

0 1 1<br />

1 1 0<br />

Fig. Fig. Fig. 20.10 20.10 Results of combining two bits with the bitwise exclusive OR opera<strong>to</strong>r (^).<br />

The bitwise complement opera<strong>to</strong>r (~) sets all 1 bits in its operand <strong>to</strong> 0 in the result and<br />

sets all 0 bits <strong>to</strong> 1 in the result—otherwise referred <strong>to</strong> as “taking the one's complement of<br />

the value.” The fourth output window for Fig. 20.8 shows the results of taking the one’s<br />

complement of the value 21845. The result is -21846.<br />

The program of Fig. 20.11 demonstrates the left shift opera<strong>to</strong>r () and the right shift opera<strong>to</strong>r with zero extension (>>>).<br />

Method getBits (lines 113–138) obtains a String containing the bit representation of<br />

the integer values. The program allows the user <strong>to</strong> enter an integer in<strong>to</strong> a JTextField<br />

and press Enter <strong>to</strong> display the bit representation of the integer in a second JTextField.<br />

The the user can press a but<strong>to</strong>n representing a shift operation <strong>to</strong> perform a 1-bit shift and<br />

view the results of the shift in both integer and bitwise representation.<br />

1 // Fig. 20.11: BitShift.java<br />

2 // Using the bitwise shift opera<strong>to</strong>rs.<br />

3<br />

4 // <strong>Java</strong> core packages<br />

5 import java.awt.*;<br />

6 import java.awt.event.*;<br />

7<br />

8 // <strong>Java</strong> extension packages<br />

9 import javax.swing.*;<br />

10<br />

11 public class BitShift extends JFrame {<br />

12 private JTextField bitsField;<br />

13 private JTextField valueField;<br />

14<br />

15 // set up GUI<br />

16 public BitShift()<br />

17 {<br />

18 super( "Shifting bits" );<br />

19<br />

20 Container container = getContentPane();<br />

21 container.setLayout( new FlowLayout() );<br />

22<br />

23 container.add( new JLabel( "Integer <strong>to</strong> shift " ) );<br />

24<br />

25 // textfield for user <strong>to</strong> input integer<br />

26 valueField = new JTextField( 12 );<br />

Fig. Fig. 20.11 20.11 Demonstrating the bitwise shift opera<strong>to</strong>rs (part 1 of 5).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!