0

Java. I want to make an array of binary numbers available in negative form but I want the original positive binary numbers to remain there as well so I can use both positive and negative numbers in my program, but I can't find out a way to convert all the binary numbers I have in my array to negative binary numbers.

    class Logicgates {
    public static void main (String args[]) {
        String binary[] = {
"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"
        };
        int a = 3;
        int b = 5;
        int c = a | b; // 0010|0100 = 0110 
        int d = a & b; // 0010&0100 = 0000
        int ff= a ^ b;
        int f = ~((~a&b) ^ (~b | a)); 
        int g = ~f | 0x0f;
        System.out.println("a = " + binary[a]);
        System.out.println("b = " + binary[b]);
        System.out.println("c = " + binary[c]);
        System.out.println("d = " + binary[d]);
        System.out.println("ff = " + binary[ff]);
        System.out.println("f = " + binary[f]);
        System.out.println("g = " + binary[g]);
    }
}

here the value of g is -1 but since my array only contains positive 1 I can't print it.

jrmullen
  • 346
  • 5
  • 21
qk2905
  • 55
  • 6

1 Answers1

0

If you want to use your original array I completely understand, as it may be a requirement to your assignment / project / learning experience.

If not, Java actually has a built in function in the java.lang library that will convert a decimal number to a binary number. The output may not be exactly what you are looking for, so you may have to make a few changes.

import java.lang.*;
public static void main(String[] args) {

    int positive = 14;
    System.out.println("Positive Number = " + positive);

    int negative = -14;
    System.out.println("Negative Number = " + negative);

   //to binary
    System.out.println("Positive Binary is " + Integer.toBinaryString(positive));
    System.out.println("Negative Binary is " + Integer.toBinaryString(negative));
    }

The output for this snippet will be

Positive Number = 14
Negative Number = -14
Positive Binary is 1110
Negative Binary is 11111111111111111111111111110010

As you can see, the negative number outputs the entire 32-bit string, but it should be simple enough for you to trim it down to the size you are looking for (e.g. 4-bit or 5-bit).

With this approach you won't be required to have your array of binary strings. You can simply pass the number to the toBinaryString() function and it will convert it for you.

After that you just need to add your logic for the gates you are trying to simulate.

Hopefully this points you in the right direction. Good luck!

jrmullen
  • 346
  • 5
  • 21