import java.awt.*;
import java.awt.event.*;
/*
RUN THIS PROGRAM AND ENTER 2 VALUES(+ve or -ve), then CLICK ON
THE OPERATOR BUTTON...SEE THE RESULT in binary(exactly the
way it is stored in memory).
*/
class BinApp extends Frame {
TextField T1, T2;
Label Result, Error;
Button bAND, bOR, bXOR, bRShift, bLShift,bRRShift;
BinApp(){
Panel P = new Panel();
Panel P_edit = new Panel();
Panel P_btn = new Panel();
Panel P_result = new Panel();
add(P, "Center");
P.setLayout(new GridLayout(3, 0));
P.add(P_edit);
T1 = new TextField(20);
T2 = new TextField(20);
P_edit.add(T1);
P_edit.add(T2);
P.add(P_btn);
bAND = new Button("&");
bOR = new Button("|");
bXOR = new Button("^");
bRShift = new Button(">>");
bLShift = new Button("<<");
bRRShift = new Button(">>>");
P_btn.setLayout(new GridLayout(3, 0));
P_btn.add(bAND);
P_btn.add(bOR );
P_btn.add(bXOR);
P_btn.add(bRShift);
P_btn.add(bLShift);
P_btn.add(bRRShift);
P.add(P_result);
Result = new Label(" ");
Error = new Label("");
P_result.setLayout(new GridLayout(2, 0));
P_result.add(Result);
P_result.add(Error);
ButtonHandler handler = new ButtonHandler();
bAND.addActionListener(handler);
bOR.addActionListener(handler);
bXOR.addActionListener(handler);
bRShift.addActionListener(handler);
bLShift.addActionListener(handler);
bRRShift.addActionListener(handler);
Error.setForeground(Color.red);
}
class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
Error.setText("");
String s = e.getActionCommand();
int n1 = getInt(T1.getText());
int n2 = getInt(T2.getText());
if (s=="&")
Result.setText(printBin(n1&n2));
else if (s=="|")
Result.setText(printBin(n1|n2));
else if (s=="^")
Result.setText(printBin(n1^n2));
else if (s==">>")
Result.setText(printBin(n1>>n2));
else if (s=="<<")
Result.setText(printBin(n1<
Result.setText(printBin(n1>>>n2));
}
}
int getInt(String s)
{
int n1 = 0;
try
{
n1 = Integer.parseInt(s);
}
catch(Exception e)
{
Error.setText("Illegal integer #: " + s);
}
return n1;
}
String printBin(int x)
{
String result = "";
int filter = 0x40000000;
try
{
if ((x & 0x80000000) == 0x80000000)//This is sign bit
result = result + "1";
else
result = result + "0";
for (int i=0; i < 31; i++)
{
if ((filter & x) == filter)
result = result + "1";
else
result = result + "0";
filter = filter >> 1;
}
}
catch(Exception e)
{
System.out.println("ERROR");
}
return result;
}
}
public static void main(String[] arg) {
BinApp a = new BinApp();
a.setSize(250,200);
a.setVisible(true);
}
}
No comments:
Post a Comment