Getting string index out of range but I don't understand why I've went through it about 50 times
import java.util.Scanner;
public class binary {
public static void main(String[] args) {
System.out.println("Enter the first binary number");
Scanner keyboard = new Scanner(System.in);
String num1 = keyboard.next();
//System.out.println("Enter the second binary number");
//String num2 = keyboard.next();
int total = 0;
for(int i = num1.length(); i>0;i--) {
if(num1.charAt(i) == 1) {
total += 2*i;
}
}
if(num1.charAt(3) == 1) {
total -= 1;
}
System.out.println(total);
}
}
Here's a complete solution to what you're trying to do, including a set of tests:
class binary {
private static int binaryToInt(String binary) {
int total = 0;
for (int i = 0 ; i < binary.length(); i++) {
total *= 2;
if (binary.charAt(i) == '1')
total += 1;
}
return total;
}
private static void test(String binary, int expected) {
int n = binaryToInt(binary);
String rightWrong = "right";
if (n != expected) {
rightWrong = String.format("WRONG! (should be %d)", expected);
System.out.printf("%s -> %d is %s\n", binary, n, rightWrong);
}
public static void main(String[] args) {
test("0", 0);
test("1", 1);
test("10", 2);
test("100", 4);
test("111", 7);
test("0000111", 7);
test("1010101010", 682);
test("1111111111", 1023);
System.out.println("");
// test sanity check
System.out.println("This last test should fail (we are just testing the test method itself here)...");
test("1010101010", 0);
}
}
Result:
0 -> 0 is right
1 -> 1 is right
10 -> 2 is right
100 -> 4 is right
111 -> 7 is right
0000111 -> 7 is right
1010101010 -> 682 is right
1111111111 -> 1023 is right
This last test should fail (we are just testing the test method itself here)...
1010101010 -> 682 is WRONG! (should be 0)
One significant problem in your code hasn't yet been addressed in the comments or earlier answers. Note this line vs the one in your code:
if (binary.charAt(i) == '1')
You were testing for the numeric value 1, which is never going to be true because you're getting back a character from charAt(), not a number.
While length() counts the number of elements, their indexes start at 0. For a string of "1111" the last character would be at index 3, not 4, so .length()-1. You would need to either change your for statement to for(int i = num1.length()-1; i>=0;i--) (notice also the condition change) or change the charAt statement to if(num1.charAt(i-1) == '1').
Also, based on what you are trying to do, I assume for total += 2*i you actually need something like total += Math.pow(2, i-length()) depending on what you decide to do with i first.
I am trying to add two binary numbers and then get their sum in binary system. I got their sum in decimal and now I am trying to turn it into binary. But there is problem that when I take their sum (in decimal) and divide by 2 and find remainders(in while loop), I need to put remainders into array in order print its reverse. However, there is an error in array part. Do you have any suggestions with my code? Thanks in advance.
Here is my code:
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int k = dec1(n)+dec2(m);
int i=0,c;
int[] arr= {};
while(k>0) {
c = k % 2;
k = k / 2;
arr[i++]=c; //The problem is here. It shows some //error
}
while (i >= 0) {
System.out.print(arr[i--]);
}
}
public static int dec1(int n) {
int a,i=0;
int dec1 = 0;
while(n>0) {
a=n%10;
n=n/10;
dec1= dec1 + (int) (a * Math.pow(2, i));
i++;
}
return dec1;
}
public static int dec2(int m) {
int b,j=0;
int dec2 = 0;
while(m>0) {
b=m%10;
m=m/10;
dec2= dec2 + (int) (b * Math.pow(2, j));
j++;
}
return dec2;
}
}
Here:
int[] arr= {};
creates an empty array. Arrays don't grow dynamically in Java. So any attempt to access any index of arr will result in an ArrayIndexOutOfBounds exception. Because empty arrays have no "index in bounds" at all.
So:
first ask the user for the count of numbers he wants to enter
then go like: int[] arr = new int[targetCountProvidedByUser];
The "more" real answer would be to use List<Integer> numbersFromUsers = new ArrayList<>(); as such Collection classes allow for dynamic adding/removing of elements. But for a Java newbie, you better learn how to deal with arrays first.
Why are you using two different methods to do the same conversion? All you need is one.
You could have done this in the main method.
int k = dec1(n)+dec1(m);
Instead of using Math.pow which returns a double and needs to be cast, another alternative is the following:
int dec = 0;
int mult = 1;
int bin = 10110110; // 128 + 48 + 6 = 182.
while (bin > 0) {
// get the right most bit
int bit = (bin % 10);
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// Sum up each product, multiplied by a running power of 2.
// this is required since bits are taken from the right.
dec = dec + mult * bit;
bin /= 10;
mult *= 2; // next power of 2
}
System.out.println(dec); // prints 182
An alternative to that is to use a String to represent the binary number and take the bits from the left (high order position).
String bin1 = "10110110";
int dec1 = 0;
// Iterate over the characters, left to right (high to low)
for (char b : bin1.toCharArray()) {
// convert to a integer by subtracting off character '0'.
int bit = b - '0';
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// going left to right, first multiply by 2 and then add the bit
// Each time thru, the sum will be multiplied by 2 which shifts everything left
// one bit.
dec1 = dec1 * 2 + bit;
}
System.out.println(dec1); // prints 182
One possible way to display the result in binary is to use a StringBuilder and simply insert the converted bits to characters.
public static String toBin(int dec) {
StringBuilder sb = new StringBuilder();
while (dec > 0) {
// by inserting at 0, the bits end up in
// correct order. Adding '0' to the low order
// bit of dec converts to a character.
sb.insert(0, (char) ((dec & 1) + '0'));
// shift right for next bit to convert.
dec >>= 1;
}
return sb.toString();
}
I need to add two binary numbers and return the sum. No base conversions are allowed. I know the long method, using arrays. But is there anything shorter ? And by shorter I mean "having smaller code length". Thanks in advance.
In case I was not explicit enough, here is an example:
Input:
1101
11
Output: 10000
The sum of two (binary) integers a and b can be computed as a+b, because all arithmetic is done in binary.
If your input is in human readable strings rather than binary, you can compute their sum in binary using the standard BigInteger class:
import java.math.BigInteger;
String sum(String a, String b) {
return new BigInteger(a, 2).add(new BigInteger(b, 2)).toString(2);
}
Represent the binary numbers as two strings. Reverse the two strings. Then, you can iterate along both strings simultaneously, adding values to three arrays, two which represent the binary digit being added from the strings and the third to represent the carry digit. Create a fourth array representing the answer (you might have to find the limit for how long the answer can possibly be).
fill the answer array by using standard binary adding:
0 + 0 = 0 in the same position,
1 + 0 = 0 + 1 = 1 in the same position,
1 + 1 = 0 in the same position, and carry a 1 to the next position,
1 + 1 + 1 = 1 in the same position, and carry a 1 to the next position.
Reverse the array and you'll have the answer as a binary number.
Here are a couple options, not using any utility methods provided by Java. These don't account for sign (leading +/-) so they only handle whole numbers.
This first method converts the binary strings to integers, adds the integers, then converts the result back to binary. It uses a method-local inner class Convert to avoid duplicating the binaryToInt() code for each of the parameters.
static String binaryAdd1(String binary1, String binary2) {
class Convert {
int binaryToInt(String binary) {
int result = 0;
for (int i = 0; i < binary.length(); i++) {
char c = binary.charAt(i);
result *= 2;
if (c == '1') {
result++;
} else if (c != '0') {
throw new IllegalArgumentException(binary);
}
}
return result;
}
}
final Convert convert = new Convert();
int int1 = convert.binaryToInt(binary1);
int int2 = convert.binaryToInt(binary2);
String result = "";
int temp = int1 + int2;
do {
result = ((temp & 1) == 1 ? '1' : '0') + result;
temp >>= 1;
} while (temp > 0);
return result;
}
This second method uses binary addition logic, as specified by JHaps in his answer, to directly add together the two parameters. No intermediate conversion to integers here.
static String binaryAdd2(String binary1, String binary2) {
final String validDigits = "01";
String binarySum = "";
// pad the binary strings with one more significant digit for carrying
String bin1 = '0' + binary1;
String bin2 = '0' + binary2;
// add them together starting from least significant digit
int index1 = bin1.length() - 1;
int index2 = bin2.length() - 1;
boolean carry = false;
while (index1 >= 0 || index2 >= 0) {
char char1 = bin1.charAt(index1 >= 0 ? index1 : 0);
char char2 = bin2.charAt(index2 >= 0 ? index2 : 0);
if (validDigits.indexOf(char1) < 0)
throw new NumberFormatException(binary1);
if (validDigits.indexOf(char2) < 0)
throw new NumberFormatException(binary2);
if (char1 == char2) {
binarySum = (carry ? '1' : '0') + binarySum;
carry = char1 == '1';
} else {
binarySum = (carry ? '0' : '1') + binarySum;
}
index1--;
index2--;
}
if (binarySum.length() > 1 && binarySum.charAt(0) == '0') {
binarySum = binarySum.substring(1);
}
String result = binarySum.toString();
return result;
}
For example, I need to grab an unknown number, let's say 3, and find the binary (2^3) - 1 times, from 0 to 111 (0-7). Obviously, the number of digits I need depends on whatever number 'n' in 2^n.
So, if the number is 3, I would need the output to be:
000
001
010
011
100
101
111
Now obviously I can do this manually with a String.format("%03d", NumberInBinary) operation, but that's hardcoding it for 3 digits. I need to do the equivalent code with an unknown number of digits, how can I do that? (as in String.format("%0nd", yournumber) where n is the number of digits.)
if n = 4, NumberInBinary = 101;
String.format("%0"+n+"d", NumberInBinary);
with output
0101
Why not make use of the already built-in Integer.toBinaryString() and just manually add the zeros using a StringBuilder ?
public static void main(String[] args) {
int max = 5;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String binary = Integer.toBinaryString(i);
if (binary.length() > max) {
break;
}
System.out.println( prefixWithZeros(binary, max) );
}
}
static String prefixWithZeros(String binary, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n - binary.length(); i++) {
sb.append('0');
}
return sb.append(binary).toString();
}
You could use recursion:
public static void enumerate(String prefix, int remaining) {
if (remaining == 0) {
System.out.println(prefix);
} else {
enumerate(prefix + "0", remaining - 1);
enumerate(prefix + "1", remaining - 1);
}
}
and then call enumerate("", numberOfDigits);
faster, using StringBuffer:
public static void enumerate(StringBuffer prefix, int remaining) {
if (remaining == 0) {
System.out.println(prefix.toString());
} else {
enumerate(prefix.append('0'), remaining - 1);
prefix.deleteCharAt(prefix.length() - 1);
enumerate(prefix.append('1'), remaining - 1);
prefix.deleteCharAt(prefix.length() - 1);
}
}
and then call enumerate(new StringBuffer(), numberOfDigits);
I have a number and I want to print it in binary. I don't want to do it by writing an algorithm.
Is there any built-in function for that in Java?
Assuming you mean "built-in":
int x = 100;
System.out.println(Integer.toBinaryString(x));
See Integer documentation.
(Long has a similar method, BigInteger has an instance method where you can specify the radix.)
Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int, representation)
Integer.toString(100,8) // prints 144 --octal representation
Integer.toString(100,2) // prints 1100100 --binary representation
Integer.toString(100,16) //prints 64 --Hex representation
System.out.println(Integer.toBinaryString(343));
I needed something to print things out nicely and separate the bits every n-bit. In other words display the leading zeros and show something like this:
n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111
So here's what I wrote:
/**
* Converts an integer to a 32-bit binary string
* #param number
* The number to convert
* #param groupSize
* The number of bits in a group
* #return
* The 32-bit long bit string
*/
public static String intToString(int number, int groupSize) {
StringBuilder result = new StringBuilder();
for(int i = 31; i >= 0 ; i--) {
int mask = 1 << i;
result.append((number & mask) != 0 ? "1" : "0");
if (i % groupSize == 0)
result.append(" ");
}
result.replace(result.length() - 1, result.length(), "");
return result.toString();
}
Invoke it like this:
public static void main(String[] args) {
System.out.println(intToString(5463, 4));
}
public static void main(String[] args)
{
int i = 13;
short s = 13;
byte b = 13;
System.out.println("i: " + String.format("%32s",
Integer.toBinaryString(i)).replaceAll(" ", "0"));
System.out.println("s: " + String.format("%16s",
Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));
System.out.println("b: " + String.format("%8s",
Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));
}
Output:
i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101
Old school:
int value = 28;
for(int i = 1, j = 0; i < 256; i = i << 1, j++)
System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
Output (least significant bit is on 0 position):
0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0
check out this logic can convert a number to any base
public static void toBase(int number, int base) {
String binary = "";
int temp = number/2+1;
for (int j = 0; j < temp ; j++) {
try {
binary += "" + number % base;
number /= base;
} catch (Exception e) {
}
}
for (int j = binary.length() - 1; j >= 0; j--) {
System.out.print(binary.charAt(j));
}
}
OR
StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
if((n&1)==1){
binary.append(1);
}else
binary.append(0);
n>>=1;
}
System.out.println(binary.reverse());
This is the simplest way of printing the internal binary representation of an integer.
For Example: If we take n as 17 then the output will be: 0000 0000 0000 0000 0000 0000 0001 0001
void bitPattern(int n) {
int mask = 1 << 31;
int count = 0;
while(mask != 0) {
if(count%4 == 0)
System.out.print(" ");
if((mask&n) == 0)
System.out.print("0");
else
System.out.print("1");
count++;
mask = mask >>> 1;
}
System.out.println();
}
Simple and pretty easiest solution.
public static String intToBinaryString(int integer, int numberOfBits) {
if (numberOfBits > 0) { // To prevent FormatFlagsConversionMismatchException.
String nBits = String.format("%" + numberOfBits + "s", // Int to bits conversion
Integer.toBinaryString(integer))
.replaceAll(" ","0");
return nBits; // returning the Bits for the given int.
}
return null; // if the numberOfBits is not greater than 0, returning null.
}
Solution using 32 bit display mask,
public static String toBinaryString(int n){
StringBuilder res=new StringBuilder();
//res= Integer.toBinaryString(n); or
int displayMask=1<<31;
for (int i=1;i<=32;i++){
res.append((n & displayMask)==0?'0':'1');
n=n<<1;
if (i%8==0) res.append(' ');
}
return res.toString();
}
System.out.println(BitUtil.toBinaryString(30));
O/P:
00000000 00000000 00000000 00011110
Simply try it. If the scope is only printing the binary values of the given integer value. It can be positive or negative.
public static void printBinaryNumbers(int n) {
char[] arr = Integer.toBinaryString(n).toCharArray();
StringBuilder sb = new StringBuilder();
for (Character c : arr) {
sb.append(c);
}
System.out.println(sb);
}
input
5
Output
101
There are already good answers posted here for this question. But, this is the way I've tried myself (and might be the easiest logic based → modulo/divide/add):
int decimalOrBinary = 345;
StringBuilder builder = new StringBuilder();
do {
builder.append(decimalOrBinary % 2);
decimalOrBinary = decimalOrBinary / 2;
} while (decimalOrBinary > 0);
System.out.println(builder.reverse().toString()); //prints 101011001
Binary representation of given int x with left padded zeros:
org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')
You can use bit mask (1<< k) and do AND operation with number!
1 << k has one bit at k position!
private void printBits(int x) {
for(int i = 31; i >= 0; i--) {
if((x & (1 << i)) != 0){
System.out.print(1);
}else {
System.out.print(0);
}
}
System.out.println();
}
The question is tricky in java (and probably also in other language).
A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.
So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).
The safe way is to use Integer.toString(X,2); this will generate something less elegant:
-11110100110
But it works!!!
I think it's the simplest algorithm so far (for those who don't want to use built-in functions):
public static String convertNumber(int a) {
StringBuilder sb=new StringBuilder();
sb.append(a & 1);
while ((a>>=1) != 0) {
sb.append(a & 1);
}
sb.append("b0");
return sb.reverse().toString();
}
Example:
convertNumber(1) --> "0b1"
convertNumber(5) --> "0b101"
convertNumber(117) --> "0b1110101"
How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).
for(int i = 1; i <= 256; i++)
{
System.out.print(i + " "); //show integer
System.out.println(Integer.toBinaryString(i) + " "); //show binary
System.out.print(Integer.toOctalString(i) + " "); //show octal
System.out.print(Integer.toHexString(i) + " "); //show hex
}
Try this way:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100
Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number.
Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number.
The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int integer ;
String binary = ""; // here we count "" or null
// just String binary = null;
System.out.print("Enter the binary Number: ");
integer = sc.nextInt();
while(integer>0)
{
int x = integer % 2;
binary = x + binary;
integer = integer / 2;
}
System.out.println("Your binary number is : "+binary);
System.out.println("your binary length : " + binary.length());
}
}
Since no answer is accepted, maybe your question was about how to store an integer in an binary-file.
java.io.DataOutputStream might be what you're looking for: https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html
DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();
Integer.toString(value,numbersystem) --- syntax to be used
and pass value
Integer.toString(100,8) // prints 144 --octal
Integer.toString(100,2) // prints 1100100 --binary
Integer.toString(100,16) //prints 64 --Hex
This is my way to format an output of the Integer.toBinaryString method:
public String toBinaryString(int number, int groupSize) {
String binary = Integer.toBinaryString(number);
StringBuilder result = new StringBuilder(binary);
for (int i = 1; i < binary.length(); i++) {
if (i % groupSize == 0) {
result.insert(binary.length() - i, " ");
}
}
return result.toString();
}
The result for the toBinaryString(0xABFABF, 8) is "10101011 11111010 10111111"
and for the toBinaryString(0xABFABF, 4) is "1010 1011 1111 1010 1011 1111"
It works with signed and unsigned values used powerful bit manipulation and generates the first zeroes on the left.
public static String representDigits(int num) {
int checkBit = 1 << (Integer.SIZE * 8 - 2 ); // avoid the first digit
StringBuffer sb = new StringBuffer();
if (num < 0 ) { // checking the first digit
sb.append("1");
} else {
sb.append("0");
}
while(checkBit != 0) {
if ((num & checkBit) == checkBit){
sb.append("1");
} else {
sb.append("0");
}
checkBit >>= 1;
}
return sb.toString();
}
`
long k=272214023L;
String long =
String.format("%64s",Long.toBinaryString(k)).replace(' ','0');
String long1 = String.format("%64s",Long.toBinaryString(k)).replace(' ','0').replaceAll("(\d{8})","$1 ");
`
print :
0000000000000000000000000000000000000000000
00000000 00000000 00000000 00000000 0000000