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;
}
Related
For example, if I have
long binarynumber=10011;
and I want it to do
binarynumber=binarynumber>>1;
But instead of discarding the rightmost number(the number would be 01001 in 5 digits), I want it to be 11001 where the last number moves to the first place in the binary "string". The value of the binary number doesn't really matter, since I am using it as a string to output.
Are you talking about doing something like this
public static String circularShiftBinary(long binaryNumber, int shift)
{
String bin = Long.toString(binaryNumber);
//check that the shift isn't a fully circular shift
if(shift % bin.length() != 0)
while(shift-- > 0)
bin = bin.charAt(bin.length() - 1) + bin.substring(0, bin.length() - 1);
return bin;
}
Example call for variations
public static void main(String[] args) {
long binaryNumber = 10011;
int shift = 0;
while(shift < 6)
System.out.println(circularShiftBinary(binaryNumber, shift++));
}//main method
Output
10011
11001
11100
01110
00111
10011
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!
Is there a way to convert an int to binary number without using Integer.toBinaryString method?
I tried to figure out the algorithm for the conversion but haven't had any luck with it.
My task is this: (https://open.kattis.com/problems/reversebinary)
Insert an Int with help of Scanner.
Convert the Int to binary.
Reverse the binary.
Print out the new Int.
For example, the number 11 is 1011 in binary.
Now reverse the binary number 1011 and you get 1101 (which is the number 13)
and print out 13.
This is what I got, but still, I used the Integer.toBinaryString method and I get NumberFormatException.
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toString(number, 2);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
}
First of all, you should use the correct terms. You are not converting an int to a binary. The int type (as well as all numeric types) are already stored in a binary format. When you convert an int to a String, or a String to an int, you choose the radix that the String representation uses (such as decimal, binary, octal, hexadecimal, etc..). This determines the digits that appear in the String representation. Now, based on your example, what you wish to do is generate a number whose binary representation is the reverse of the input number. In other words, you want to reverse the bits of the input number.
Your current loop :
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
calculates the decimal (radix 10) digits of binary and creates an integer whose value is the value of those digits when they are arranged in reversed order.
If you want the reverse of the binary representation of the input number, you should multiply and divide by 2 in order to obtain the binary digits (aka bits) of the input number and reverse them :
while (number != 0) {
System.out.print (number % 2); // prints a binary digit (i.e. 0 or 1)
reverse = reverse * 2 + number % 2;
number = number / 2;
}
System.out.println();
System.out.println(reverse); // prints the decimal representation of the reversed number
If number is 11, reverse will be 13, since the reverse of 1011 is 1101. This code will print both the binary representation of the reversed number (1101) and the decimal representation (13).
Instead of reversing the binary as a number, reverse it while it is still a String, new StringBuilder(b).reverse().toString(). Then convert it back to an int from base 2, and you're done.
So the entire code would be:
final Scanner scn = new Scanner(System.in);
final int number = scn.nextInt();
String b = Integer.toString(number, 2);
b = new StringBuilder(b).reverse().toString();
System.out.println(Integer.parseInt(b.toString(), 2));
Maybee the smartest solution for this problem is bit shifting. I wrote an example with a little explanation.
int number, reverse = 0;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
while (number > 0)
{
// shift all bits to the left
reverse = reverse << 1;
// extract the last bit of the number
int bit = number & 1;
// add the last bit to the reverse version
reverse |= bit;
// shift alle bits to the right
number = number >> 1;
}
System.out.println(reverse);
Integer.toBinaryString - Returns a string representation of the integer argument as an unsigned integer in base 2.
String toString(int i, int radix) -
Returns a string representation of the first argument in the radix specified by the second argument
public static void main(String[] args) {
int reverse = 0;
int number, binary;
Scanner scn = new Scanner(System.in);
number = scn.nextInt();
String b = Integer.toBinaryString(number);
binary = Integer.parseInt(b);
while (binary != 0) {
reverse = reverse * 10 + binary % 10;
binary = binary / 10;
}
int newNumber = Integer.parseInt(String.valueOf(reverse), 2);
System.out.println(newNumber);
}
Infact whatever you use cannot give an error. The above code perfectly compiles without an error.
Providing 11, gives 13 perfectly.
I am trying to represent the number .0002 as 2.0 x 10 ^ -4.
Here is what I have so far
public static String toScientificNotation(double n) {
int exponent = 0;
if( n < 1){
String doubleValue = Double.toString(Math.abs(n));
int format = doubleValue.indexOf(".");
int decimalPlacesToMove = (doubleValue.length() - (format - 1));
}
No matter what I try i get E in the output. If someone can give me a pseudo code. It would be a great help. I cannot use BigDecimal or anything other than double.
I reworked your method into the following; you can use it as a basis/skeleton to convert the double into the scientific notation you want, avoiding the E altogether. You can expand on it by creating implementations for n > 1 and n < 0
private static String toScienticNotation(double n) {
String result = "";
if (n < 1 && n > 0) {
int counter = 0;
double answer = n;
while (answer < 1) {
answer = answer * 10;
counter--;
}
result = String.valueOf(answer) + " x 10 ^ "
+ String.valueOf(counter);
}
return result;
}
It works by multiplying the input n by 10, counter number of times, until n is greater than 1. This is a substitute formula to manually discover the number of decimal points rather than using the String methods.
The method you were using would work fine, but there's an easier way using formatter:
import java.util.*;
import java.text.*;
import java.math.*;
class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
NumberFormat formatter = new DecimalFormat();
double d = input.nextDouble();
formatter = new DecimalFormat("#.######E0");
String x = formatter.format(d);
System.out.println(x.replace("E","*10^");
}
}
This will print the scientific notation in the decimal format of #.######E0
For example:
If 200 was inputted, the system would return 2 * 10^2.
Here is a method which (hopefully) converts all kinds of doubles to their [-]Factor * 10 ^ [-]Exponent notation. It's explained inside the code.
edit: There is a very elegant solution by UnknownOctopus. Still I will leave this here as it does not use any formatters or such, just doubles and Strings - I understood the question wrongly and assumed that only such primitives were allowed.
public class Main{
/**
* Converts a double to a base10 notation String.
*
* Each String is formatted like this:
*
* [-]Factor * 10 ^ [-]Exponent
*
* where both, Factor and Exponent, are integer values.
*
* #param number the number to convert
* #return a base10 notation String.
*/
public static String toScientificNotation(double number) {
String s = String.valueOf(number);
int indexPZero = s.indexOf(".0"); // mostly to check if .0 is the end
int exponent = 0; // simplest case: *10^0
// Check if the String ends with exactly .0
if (indexPZero == s.length() - 2) {
// If the string also has 0s in front of the period, shift those to the
// right
while(s.contains("0.")) {
number /= 10;
exponent += 1;
s = String.valueOf(number);
}
// if the string ends in .0 and has no zeros in front of the period we
// can format it:
return String.valueOf(number) + " * 10 ^ " + exponent;
}
// If the String does not end in .0, we need to shift to the left.
// Additionall
while (indexPZero != s.length() -2) {
// in case we suddenly reach the scientific notation just substitute it
s = s.toLowerCase();
if (s.contains("e")) {
return s.substring(0,
s.indexOf("e")) + " * 10 ^ " + s.substring(s.indexOf("e")+1);
}
// otherwise shift left and reduce the exponent
number *= 10;
exponent -= 1;
s = String.valueOf(number);
indexPZero = s.indexOf(".0");
}
// If we end up here, just write out the number and the exponent.
return String.valueOf(number) + " * 10 ^ " + exponent;
}
public static void main(String... args) {
double[] vals = { 1, 0.2, 23.4, -32.00004, 0.0002, 10.0 };
for(double val : vals) {
System.out.println(val + " becomes " + toScientificNotation(val));
}
}
}
Output:
1.0 becomes 1.0 * 10 ^ 0
0.2 becomes 2.0 * 10 ^ -1
23.4 becomes 234.0 * 10 ^ -1
-32.00004 becomes -3200004.0 * 10 ^ -5
2.0E-4 becomes 2.0 * 10 ^ -4
10.0 becomes 1.0 * 10 ^ 1
I'm trying to store a number as a binary string in an array but I need to specify how many bits to store it as.
For example, if I need to store 0 with two bits I need a string "00". Or 1010 with 6 bits so "001010".
Can anyone help?
EDIT: Thanks guys, as I'm rubbish at maths/programming in general I've gone with the simplest solution which was David's. Something like:
binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
binaryString.insert(0, "0");
}
It seems to work fine, so unless it's very inefficient I'll go with it.
Use Integer.toBinaryString() then check the string length and prepend it with as many zeros as you need to make your desired length.
Forget about home-made solutions. Use standard BigInteger instead. You can specify number of bits and then use toString(int radix) method to recover what you need (I assume you need radix=2).
EDIT: I would leave bit control to BigInteger. The object will internally resize its bit buffer to fit the new number dimension. Moreover arithmetic operations can be carried out by means of this object (you do not have to implement binary adders/multipliers etc.). Here is a basic example:
package test;
import java.math.BigInteger;
public class TestBigInteger
{
public static void main(String[] args)
{
String value = "1010";
BigInteger bi = new BigInteger(value,2);
// Arithmetic operations
System.out.println("Output: " + bi.toString(2));
bi = bi.add(bi); // 10 + 10
System.out.println("Output: " + bi.toString(2));
bi = bi.multiply(bi); // 20 * 20
System.out.println("Output: " + bi.toString(2));
/*
* Padded to the next event number of bits
*/
System.out.println("Padded Output: " + pad(bi.toString(2), bi.bitLength() + bi.bitLength() % 2));
}
static String pad(String s, int numDigits)
{
StringBuffer sb = new StringBuffer(s);
int numZeros = numDigits - s.length();
while(numZeros-- > 0) {
sb.insert(0, "0");
}
return sb.toString();
}
}
This is a common homework problem. There's a cool loop that you can write that will compute the smallest power of 2 >= your target number n.
Since it's a power of 2, the base 2 logarithm is the number of bits. But the Java math library only offers natural logarithm.
math.log( n ) / math.log(2.0)
is the number of bits.
Even simpler:
String binAddr = Integer.toBinaryString(Integer.parseInt(hexAddr, 16));
String.format("%032", new BigInteger(binAddr));
The idea here is to parse the string back in as a decimal number temporarily (one that just so happens to consist of all 1's and 0's) and then use String.format().
Note that you basically have to use BigInteger, because binary strings quickly overflow Integer and Long resulting in NumberFormatExceptions if you try to use Integer.fromString() or Long.fromString().
Try this:
String binaryString = String.format("%"+Integer.toString(size)+"s",Integer.toBinaryString(19)).replace(" ","0");
where size can be any number the user wants
Here's a simple solution for int values; it should be obvious how to extend it to e.g. byte, etc.
public static String bitString(int i, int len) {
len = Math.min(32, Math.max(len, 1));
char[] cs = new char[len];
for (int j = len - 1, b = 1; 0 <= j; --j, b <<= 1) {
cs[j] = ((i & b) == 0) ? '0' : '1';
}
return new String(cs);
}
Here is the output from a set of sample test cases:
0 1 0 0
0 -1 0 0
0 40 00000000000000000000000000000000 00000000000000000000000000000000
13 1 1 1
13 2 01 01
13 3 101 101
13 4 1101 1101
13 5 01101 01101
-13 1 1 1
-13 2 11 11
-13 3 011 011
-13 4 0011 0011
-13 5 10011 10011
-13 -1 1 1
-13 40 11111111111111111111111111110011 11111111111111111111111111110011
Of course, you're on your own to make the length parameter adequate to represent the entire value.
import java.util.BitSet;
public class StringifyByte {
public static void main(String[] args) {
byte myByte = (byte) 0x00;
int length = 2;
System.out.println("myByte: 0x" + String.valueOf(myByte));
System.out.println("bitString: " + stringifyByte(myByte, length));
myByte = (byte) 0x0a;
length = 6;
System.out.println("myByte: 0x" + String.valueOf(myByte));
System.out.println("bitString: " + stringifyByte(myByte, length));
}
public static String stringifyByte(byte b, int len) {
StringBuffer bitStr = new StringBuffer(len);
BitSet bits = new BitSet(len);
for (int i = 0; i < len; i++)
{
bits.set (i, (b & 1) == 1);
if (bits.get(i)) bitStr.append("1"); else bitStr.append("0");
b >>= 1;
}
return reverseIt(bitStr.toString());
}
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}
Output:
myByte: 0x0
bitString: 00
myByte: 0x10
bitString: 001010
So here instead of 8 you can write your desired length and it will append zeros accordingly. If the length of your mentioned integer exceeds that of the number mentioned then it will not append any zeros
String.format("%08d",1111);
Output:00001111
String.format("%02d",1111);
output:1111