convert array numbers to negative - java

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.

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!

Related

How would I add two int that are in the same array to each other and convert them into an int. In the Luhn Algorithm

I am trying to add two parts of an array together to go into an int value. I am using Luhn algorithm to figure out of a credit card is a valid credit card. We are only using 6 digit credit card's just to make sure no one enter's a real credit card number. The part I am confused on is when I go to split a number that is above 10 and add it together. Example if the algorithm was to give me 12 I would need to separate it into 1 and 2 and then add them together to equal 3. I believe I am splitting it currently in the code but when I go to add them together I get some number that makes no since. here is a section of the code with some notes about it.
I have printed out numbers in certain places to show myself what is going on in certain places. I have also added in some comments that say that either the number that is printed out is what is expected, and some comments for when there isn't something I expected
int[] cardNumber = new int[]{ 1,2,3,4,5,5};
int doubleVariablesum = 0;
int singleVariablesum = 0;
int totalSum = 0;
int cutOffVar = 0;
String temp2;
for (int i = cardNumber.length - 1; i >= 0;) {
int tempSum = 0;
int temp = cardNumber[i];
temp = temp * 2;
System.out.println("This is the temp at temp * 2: " + temp);
temp2 = Integer.toString(temp);
if (temp2.length() == 1) {
System.out.println("Temp2 char 0: "+ temp2.charAt(0));
// this prints out the correct number
// Example: if there number should be 4 it will print 4
tempSum = temp2.charAt(0);
System.out.println("This is tempSum == 1: " + tempSum);
// when this goes to add temp2.charAt(0) which should be 4 it prints out //something like 56
} else {
System.out.println("TEMP2 char 0 and char 1: " + temp2.charAt(0) + " " + temp2.charAt(1));
// this prints out the correct number successfully spited
tempSum = temp2.charAt(0) + temp2.charAt(1);
System.out.println("This is tempSum != 1: " + tempSum);
// but here it when I try to add them together it is giving me something
// like 97 which doesn't make since for the numbers I am giving it
}
doubleVariablesum = tempSum + doubleVariablesum;
System.out.println("This is the Double variable: " + doubleVariablesum);
System.out.println();
i = i - 2;
}
Since you are converting the number to a string to split the integer, and then trying to add them back together. You're essentially adding the two characters numerical values together which is giving you that odd number. You would need to convert it back to an integer, which you can do by using
Integer.parseInt(String.valueOf(temp2.charAt(0)))
When adding char symbols '0' and '1' their ASCII values are added - not numbers 0 and 1.
It is possible to use method Character::getNumericValue or just subtract '0' when converting digit symbol to int.
However, it is also possible to calculate sum of digits in a 2-digit number without any conversion to String and char manipulation like this:
int sum2digits = sum / 10 + sum % 10; // sum / 10 always returns 1 if sum is a total of 2 digits
Seems like charAt() type casts into integer value, but the ascii one. Hence for the characters '0' and '1', the numbers 48 and 49 are returned resulting in a sum of 97. To fix this, you could just assign temp2 to (temp / 10) + (temp % 10). Which actually splits a two digit integer and adds their sum.
You need to be aware of the following when dealing with char and String
Assigning the result of charAt(index) to an int will assign the ASCII value and not the actual integer value. To get the actual value you need to String.valueOf(temp2.charAt(0)).
The result of concatenating chars is the sum of the ASCII values.
eg if char c = '1'; System.out.println(c + c); will print "98" not "11".
However System.out.println("" + c + c); will print "11". Note the "" will force String concatenation.

Big binary number

I'm trying to solve a problem, for the basic scenario it's working, nevertheless, I know that it is not optimal and has several faults.
Problem:
You are given a number n. Find the decimal value of the number formed by the concatenation of the binary representation of the first n positive integers. Print the answer 10^9 + 7.
Output format:
Print the answer modulo 10^9 + 7
Constraint:
1 <= n <= 10^9
Sample input: 3
Sample Output: 27
The binary representation of 1: 1
The binary representation of 2: 10
The binary representation of 3: 11
Concatenated string: 11011 -> Decimal representation is 27.
The first doubt that I have is: "modulo 10^9 + 7", I understand is the limit for the number of chars, but I don't know how to interpret it.
The second part of the question is with the solution:
Input: 20
Binary representation of 2 : 10.
Binary representation of 3 : 11
Binary representation of 4 : 100.
Binary representation of 5 : 101
Binary representation of 6 : 110
Binary representation of 7 : 111
Binary representation of 8 : 1000
Binary representation of 9 : 1001
Binary representation of 10 : 1010
Binary representation of 11 : 1011
Binary representation of 12 : 1100
Binary representation of 13 : 1101
Binary representation of 14 : 1110
Binary representation of 15 : 1111
Binary representation of 16 : 10000
Binary representation of 17 : 10001
Binary representation of 18 : 10010
Binary representation of 19 : 10011
The binary representation of 20: 10100
Concatenated string: 11011100101110111100010011010101111001101111011111000010001100101001110100
How would you recommend to tackle this kind of problem?
This is my current code:
public long FindBigNum(long n) {
System.out.println("");
System.out.println("Input: " + n);
StringBuilder binaryRepresentation = new StringBuilder();
for(Long i = 1l; i <= n; i++){
System.out.println("Binary representation of " + i + " : " + Long.toBinaryString(i));
binaryRepresentation.append(Long.toBinaryString(i));
}
System.out.println("Concatenated string: " + binaryRepresentation.toString());
//System.out.println("Binary representation: " + binaryRepresentation.toString());
long longRepresentation = parseLong(binaryRepresentation.toString(), 2);
//System.out.println("longRepresentation: " + l);
return longRepresentation;
}
public long parseLong(String s, int base){
return new BigInteger(s, base).longValue();
}
public class TestClass {
static long FindBigNum(long n) {
long result = 0;
StringBuilder binary = new StringBuilder();
long binarySumLong;
long moduloFactor = (long) (Math.pow(10, 9) + 7);
for (int number = 1; number < n; number++) {
System.out.println("Number is : " + number);
String binaryRepresentation = Long.toBinaryString(number);
System.out.println("Binary representation of " + number + " is " + binaryRepresentation);
binary.append(binaryRepresentation);
System.out.println("Value of StringBuffer binary is " + binary);
binarySumLong = binaryToInteger(binary.toString());
System.out.println("binarySumLong is : " + binarySumLong);
if (binarySumLong > (moduloFactor)) {
binarySumLong = binarySumLong % (moduloFactor);
binary = new StringBuilder(Long.toBinaryString(binarySumLong));
System.out.println(" *** binary after modification is : " + binary);
System.out.println(" *** and integer value of binary is : " + binaryToInteger(binary.toString()));
}
}
result = binaryToInteger(binary.toString());
return result;
}
public static int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for (int i = numbers.length - 1; i >= 0; i--)
if (numbers[i] == '1')
result += Math.pow(2, (numbers.length - i - 1));
return result;
}
public static void main(String[] args) {
long output = FindBigNum((long) Math.pow(10, 4));
System.out.println("output is : " + output);
}
}
The first doubt that I have is: "modulo 10^9 + 7", I understand is the limit for the number of chars, but I don't know how to interpret it.
That means to get the remainder when dividing by that value. It is the value 1000000007 (I am assuming the caret is exponentiation).
Here is how I would approach this.
Generate your concatenated strings as you have been.
Use BigInteger to convert from binary to decimal and then take the mod with the BigInteger mod method.
That will ultimately be very slow and not efficient. However, it serves as a control to allow you to investigate optimal ways of doing it. Perhaps employing StringBuilder and pre-allocating storage for it. Writing your own int to binary conversion routine, etc.
It may even require more of a math solution (e.g. number theory) than a programming solution.
But you can compare your results to the BigInteger solution to verify if it is working.

How to convert char to decimal using an ascii table?

I'm working on a java program to convert a 4 digit binary number to decimal. I need to enter the binary as a String, convert to a char, and then to a decimal. I cannot use something like:
int decimal = Integer.parseInt("1010", 2);
Here is my code so far:
import java.util.Scanner;
public class BinaryConvert2 {
public static void main(String[] args){
System.out.println("Please enter a 4 digit binary number: ");
Scanner s = new Scanner(System.in);
String binaryNumber = s.next();
char a, b, c, d;
a = binaryNumber.charAt(0);
a = (char) (a*2*2*2);
b = binaryNumber.charAt(1);
b = (char) (b*2*2);
c = binaryNumber.charAt(2);
c = (char) (c*2);
d = binaryNumber.charAt(3);
d = (char) (d*1);
System.out.println(binaryNumber + " in decimal is: " + a + b + c + d);
}
}
I'm trying to multiply the char values by powers of 2 so that it will convert to decimal, but when I run the program, I get weird answers such as :
Please enter a 4 digit binary number:
1010
1010 in decimal is: ?Àb0
The ascii (char) value of 0 is 48 and the value if 1 is 49,
so you need to subtract 48 from the value
a = binaryNumber.charAt(0);
int aInt = (a - 48) * 2 * 2* 2;
....
System.out.println(binaryNumber + " in decimal is: " + (aInt + bInt + cInt + dInt));
The problem is you are printing the a b c and d as chars so it will print what ever decimal value of a b c and d correspond to in the ascii table. If you want to print out decimals you will have to convert the value to decimal by subtracting 48 add them together and then print.
Has to be like this:
1010 = 8 + 0 + 2 + 0 = 10 then print 10. You are on the right track
get the numeric value and do multiplication, if you do with char it will use the ASCII value
int num = 0;
a = binaryNumber.charAt(0);
num += (Character.getNumericValue(a) * 2 * 2 * 2);
b = binaryNumber.charAt(1);
num += (Character.getNumericValue(b) * 2 * 2);
c = binaryNumber.charAt(2);
num += (Character.getNumericValue(c) * 2);
d = binaryNumber.charAt(3);
num += (Character.getNumericValue(d) * 1);
System.out.println(binaryNumber + " in decimal is: " + num);

A java console program that converts "BINARY" to "DECIMAL" without using a predefined method using for loop [duplicate]

This question already has answers here:
A java console program that converts decimal to binary without using a predefined method (for)
(2 answers)
Closed 6 years ago.
I made a java console program that prints the decimal value of the binary value inputted. Now, I have a problem with my program that
for e.g. output:
Enter input = 10011101 then the binary value is 3534200 instead of 157
After surfing the internet for the formula in converting binary value to decimal, this is the reference I took for making this program.
1*2^7 + 0*2^6 + 0*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0 = 157.
I tried the long version in making this program, in using for loop... I guess that's a dumb challenge? haha!
here's the code(w/ comments!):
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num = Integer.parseInt(new String(b.substring(b.length() - 1).trim()));
//num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
for(int a = i; a > 0; a--){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
num = Integer.parseInt(new String(b.substring(i - 1).trim())); //uhm dunno how to describe this, but you'll see
power = 2;
}
System.out.print(formula);
}
}
ever since I started using java, this is the only thing that I know. (refer to my last question since sep 4)
please help :(
You have a number of problems:
1) Integer.parseInt(new String(binary).trim()) does not do what you think it does. Therefore, your num is wrong.
2) You calculate your power wrong.
3) A general advice, put some empty lines to separate your code into small blocks that make sense. It will be easier on the eyes.
The fixed program should look like this:
public static void main(String[] args) throws IOException {
byte binary[] = new byte[127]; //declared a byte array for input value
int power = 2, formula = 0; //declared the power and the formula as int
System.out.print("Enter Binary: "); //prints "Enter binary:"
System.in.read(binary); //inserts the input in the binary array
Integer bin = Integer.parseInt(new String(binary).trim()); //converts the input value to int for another conversion
String b = Integer.toString(bin); //converts the int bin to string
Integer num; //num variable gets the value of last string (should be anyway)
System.out.println("The Decimal Value of " + bin + " is ");
for(int i = b.length(); i > 0; i--){
power = 1;
num = Integer.parseInt(Character.toString(b.charAt(i-1)));
for(int a = i; a < b.length(); a++){ //the condition
power = power*2; //as the loop goes, if 2^3 then it should be 8
}
formula = formula + (num * (power)); //as the given formula above, this is what I did
System.out.println("power: " + power);//if you want reference, I left it here
System.out.println("formula: " +formula);
System.out.println("num: " + num);
}
System.out.print(formula);
}

How to convert a binary String to a decimal string in Java

I was working on a homework and thought I had finished but the teacher told me that it wasn't what he was looking for so I need to know how I can convert a binary number that is stored as a String to a decimal string without using any built-in function outside of length(), charAt(), power function, and floor/ceiling in Java.
This is what I had on the beginning.
import java.util.Scanner;
public class inclass2Fall15Second {
public static void convertBinaryToDecimalString() {
Scanner myscnr = new Scanner(System.in);
int decimal = 0;
String binary;
System.out.println("Please enter a binary number: ");
binary = myscnr.nextLine();
decimal = Integer.parseInt(binary, 2);
System.out.println("The decimal number that corresponds to " + binary + " is " + decimal);
}
public static void main (String[] args) {
convertBinaryToDecimalString();
}
}
To convert a base 2 (binary) representation to base 10 (decimal), multiply the value of each bit with 2^(bit position) and sum the values.
e.g. 1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11
Since binary is read from right-to-left (i.e. LSB (least significant bit) is on the rightmost bit and MSB (most-significant-bit) is the leftmost bit), we traverse the string in reverse order.
To get the bit value, subtract '0' from the char. This will subtract the ascii value of the character with the ascii value of '0', giving you the integer value of the bit.
To calculate 2^(bit position), we can keep a count of the bit position, and increment the count on each iteration. Then we can just do 1 << count to obtain the value for 2 ^ (bit position). Alternatively, you could do Math.pow(2, count) as well, but the former is more efficient, since its just a shift-left instruction.
Here's the code that implements the above:
public static int convertBinStrToInt(String binStr) {
int dec = 0, count = 0;
for (int i = binStr.length()-1; i >=0; i--) {
dec += (binStr.charAt(i) - '0') * (1 << count++);
}
return dec;
}

Categories

Resources