Decimal-to-binary conversion - java

I want to convert decimal numbers to binary numbers. I want to store them in an array.
First I need to create an array that has a certain length so that I can store the binary numbers. After that I perform the conversion, here is how I do it:
public class Aufg3 {
public static void main(String[] args) {
int[] test = decToBin(12, getBinArray(12));
for(int i = 0; i < test.length; i++){
System.out.println(test[i]);
}
}
public static int[] getBinArray(int number){
int res = number, length = 0;
while(res != 0){
res /= 2;
length++;
}
return new int[length];
}
public static int[] decToBin(int number, int[] array){
int res = number, k = array.length-1;
while(res != 0){
if(res%2 == 0){
array[k] = 0;
}else{
array[k] = 1;
}
k--;
res /= 2;
}
return array;
}
}
Is there anything to improve? It should print 1100 for input of 12.

Why not just use the toBinaryString method of the Integer class:
System.out.println(Integer.toBinaryString(12))

I assume you want to write your own code -- otherwise this is straightforward to do using methods from the standard Java library.
Some quick comments:
You can get rid of the res temp vars. Work directly on number (remember that Java passes parameters by value).
Shift is more efficient than division (number >>>= 1 instead of number /= 2), although the compiler should be able to optimize this anyway
You can avoid the modulus in decToBin if you just do array[k] = number & 1;
While you are at it, why not call getBinArray from decToBin directly? Then you can call decToBin with only one arg -- the value to convert.
Here is a slightly optimized version of your code:
public static int[] getBinArray(int number) {
int length = 0;
while (number != 0) {
number >>>= 1;
length++;
}
return new int[length];
}
public static int[] decToBin(int number) {
int[] array = getBinArray(number);
int k = array.length-1;
while (number != 0)
{
array[k--] = number & 1;
number >>>= 1;
}
return array;
}

If this isn't homework, no need to do it yourself. The following code should work:
BigInteger bigInt = new BigInteger(number);
String asString = bigInt.toString(2);
There might be more efficient ways, but this is certainly very readable and maintainable.

There are some small things that you can improve:
You should define a "high-level" method that converts an int to an int[]. In the current code you have to mention the 12 two times, which is bad.
You should use a do { ... } while (number != 0) loop. Otherwise the number 0 will be represented by an empty array.
You should use x >>> 1 instead of x / 2, since that handles negative numbers correctly.
If you want to check that your code is correct, write another method that converts back from binary to int. Then you can check that binToDec(decToBin(12, ...)) == 12.
The method getBinArray should not be public, since it is only a helper method. You can either replace the public with private or just remove the public.

Related

In Java, what is the best way to get each individual digit of an integer and its position for comparison?

New to programming: In Java, what is the best way to get each individual digit of an Integer and its position for comparisons? For example, with an input of an Integer i = 12345, I'd like to preform a comparison operation on each individual digit 1, 2, 3, 4, and 5. Since I can't get the index of the integer, I converted the integer to string, iterated, and used charAt().
String sI = Integer.toString(i);
for(int j = 0; j<i; j++){
if(charAt(j)>n){
//do something
}
}
why not try this... you will know that your int is printing from the last digit so you'll know the position.
public static void main(String[] args) {
Integer temp = 123456789;
do {
System.out.println(temp % 10);
temp = temp / 10;
} while (temp % 10 > 0);
}
I would do the same solution however your loop may result in some unexpected errors. That's because i can be greater than the length of your String sI.
And chars in Java are integers too so the comparison may fail: for example the character value of 1 is 49 so a comparison like if (sI.charAt(j) > 10) will always results in true. So you have to re-convert your character to an integer with the Character.getNumericValue() function.
So I'd change the loop to the following:
String sI = Integer.toString(i);
for(int j = 0; j < sI.length(); j++){
if(Character.getNumericValue(sI.charAt(j)) > n){
//do something
}
}
May be something like this helps
public int findallIntegers(int x, int n) {
if(x < 1) return 1;
if(x%10 > n) {
//do some thing
}
return findallIntegers(x/10, n);
}

Comparing two char arrays each representing a binary number

I need to write a method for comparing two binary numbers. I am storing the binary numbers in character arrays, so I can store big numbers (I can't use the BigInteger class or any other packages).
Example to make things clear:
char[] num1 = {'1','1','0'}
char[] num2 = {'1','1','1'}
I need to return 0 if they are equal, -1 if a < b and 1 if a > b
This is the approach I took:
static int compare(char[]a, char[]b) {
//If arrays lengths aren't equal I already know, one is bigger then the other
int a_len = a.length;
int b_len = b.length;
int a_bits = 0;
int b_bits = 0;
if (a_len > b_len)
return 1;
if (b_len > a_len)
return -1;
//I count the number of bits that are 1 in both arrays
for (int i = 0; i < a.length; i++) {
if (a[i] == '1') a_bits++;
if (b[i] == '1') b_bits++;
}
if(a_bits>b_bits)
return 1;
if(b_bits>a_bits)
return -1;
return 0;
}
So as far as I understand, this works in every case, but the case where the number of bits are equal (1100 is bigger than 1001 for example).
I was thinking I could add up the indexes in the for loop for each array and work from there, but I started thinking I may be overcomplicating things. Is this even a good approach to it? I'm starting to doubt it. Any insight is appreciated
I would look for the first index that is 1 in one of the numbers but 0 in the other number. You can replace the bit counting loop(keeping the length check) with:
for (int i = 0; i < a.length; i++) {
if (a[i] == '1' && b[i] == '0') return 1;
if (b[i] == '1' && a[i] == '0') return -1;
}
return 0;
Using some conversion and the binary parseInt offered by class Integer you can do this simple comparison regardless of the arrays' size. (I'd be careful instead with checking the length of the arrays because if you have leading zeros in one array this could bring some comparisons to miss).
String first = new String(a);
String second = new String(b);
int firstint = Integer.parseInt(first, 2);
int secondint = Integer.parseInt(second, 2);
if(firstint > secondint)
return 1;
if(firstint < secondint)
return -1;
return 0;
An alternative approach would be as follows:
Convert Array Of Characters into String.
Convert the resulting String into int.
Work out the logic from the resulting int
It will always work and you can print out the resulting conversion.
Hope this helps.
public static void main(String[] args) {
char[] num1 = {'1','1','0'};
char[] num2 = {'1','1','1'};
System.out.println(compare(num1, num2));
}
public static int compare(char[]num1, char[]num2) {
// Convert Array of Characters to String
String one = String.valueOf(num1);
String two = String.valueOf(num2);
// Convert to Integer (Binary to Decimal Conversion to base2)
int a = Integer.parseInt(one,2);
int b = Integer.parseInt(two,2);
int result = 0; // return result as equals i.e. 0.
if(a > b) { // Yes. Curly brackets are important in Java
result = 1;
} else if(a < b){
result = -1;
}
return result; // Use only one return, i.e. a variable.
}

How to swap digits in java

I am trying to practice java over the summer and i'm stuck on this problem. I need to swap the 2 letters in a integer in java. For example in my main method I make a method called swapdigits and have my parameters as 1432. The program should swap the 4 and 1 and 3 and 2. The output should be 4123 since it swapped the two letters in order. Lets say I do swapdigits(1341234) the output should be 3114324. I know I have to use while loops but i'm getting stuck on the swapping.
This is what I have so far:
public static void main(String[] args) {
Swapdigits(2413);
}
public static void Swapdigits(int number){
while(number>0){
int y=number/1000;
int x=number%10;
int original=number-y;
System.out.println(original);
}
System.out.println();
}
}
public static int swapDigitPairs(int number) {
int result = 0;
int place = 1;
while (number > 9) {
result += place * 10 * (number % 10);
number /= 10;
result += place * (number % 10);
number /= 10;
place *= 100;
}
return result + place * number;
}
You can also try
char[] a = String.valueOf(number).toCharArray();
for (int i = 0; i < a.length - 1; i += 2) {
char tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
}
int number = Integer.parseInt(new String(a));
Because you're just swapping the places of digits, it doesn't actually matter what the number is. So, it's probably easier (and makes more sense) to represent the argument as a string. That way you aren't dealing with weird modulo operators - If you were solving the problem by hand, would you actually do any math? You'd treat this problem the same whether it were numbers of a bunch of characters.
Take a look at the following question for information on swapping characters in a String:
How to swap String characters in Java?

Java program that converts binary numbers to decimal numbers. The input is a string of zeros and ones

I have to create a java program that converts binary to decimal using the following steps. Being new at this I did something, but I don't know what I did wrong or how to continue.
public class BinaryToDecimal {
public static void main(String args[]){
long sum = 0;
int result;
String s = "1001010101011010111001011101010101010101";
for(int i = s.length()-1; i <= 0; i--){
result = (int)Math.pow(2, i);
if(s.charAt(i) == '1')
sum=sum + result;
}
System.out.println(sum);
}
}
Use a loop to read (charAt()) each digit (0/1 char) in the input string, scanning from right to left;
Use the loop to build the required powers of 2;
Use a conditional statement to deal with 0 and 1 separately;
Debug using simple input, e.g. 1, 10, 101, and print intermediate values in the loop.
Use your program to find the decimal value of the following binary number:
1001010101011010111001011101010101010101
Do this only if your decimal value is at most 2147483647 or the maximum value an int can be in Java. If you don't know, just check the length of your string. If it's less than or equal to 32 i.e. 4 bytes, then you can use parseInt.:
int decimalValue = Integer.parseInt(s, 2);
Refer HERE for more info on the Integer.parseInt();
But if it's more, you can use your code. I modified your loop which is where your problem was:
String s = "1001010101011010111001011101010101010101";
long result = 0;
for(int i = 0; i < s.length(); i++){
result = (long) (result + (s.charAt(i)-'0' )* Math.pow(2, s.length()-i-1));
}
System.out.println(result);
The first thing I notice is that your binary number has more than 32 bits. This cannot be represented in the space of an int, and will result in overflow.
As a simpler answer, I ran the following and got the correct value at the end, it just uses simple bit shifts.
For each index in the string, if the character is 1, it sets the corresponding bit in the result.
public class BinaryToDecimal {
public static void main(String[] args) {
long sum;
String bin = "1001010101011010111001011101010101010101";
sum = 0;
for (int i = 0; i < bin.length(); i++) {
char a = bin.charAt(i);
if (a == '1') {
sum |= 0x01;
}
sum <<= 1;
}
sum >>= 1;
System.out.println(sum);
}
}
The loop runs from i = s.length()-1 until i <= 0. This should be i>=0.
The next problem is "int result". It works fine with result as a long ;) (Reason: You calculate a 40-bit value at the MostSignificantBit, but Integers only use 32-bit)
Also: You start at the rightmost Bit with i=s.length()-1. But the power that you calculate for it is 2^(s.length()-1) though it should be 2^0=1.
The solution is: result = (long)Math.pow(2, s.length()-1-i)
Edit:
I really like the solution of user2316981 because of its clear structure (without Math.pow, should be faster by using shift instead). And loops from 0 to MSB as I do with Double&Add algorithm. Can't comment on it yet, but thanks for the reminder ;)
import java.util.*;
import java.lang.Math;
class deci {
int convert(int n) {
int tem=1,power=0;
int decimal=0;
for (int j=0;j<n;j++) {
if(n==0) {
break;
} else {
while(n>0) {
tem=n%10;
decimal+=(tem*(Math.pow(2,power)));
n=n/10;
power++;
}
}
}
return decimal;
}
public static void main(String args[]) {
System.out.print("enter the binary no");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
deci dc=new deci();
int i=dc.convert(n);
System.out.print(i);
}
}

how to get an array of of the digits of an int in java

So this probably would be easy if done like this
public static [] nums(int j)
{
int num = 12345;
int[]thenums = [5];
for(int i=0; i<5; i++)
{
thenums[4-i] = num%10;
num = num/10;
}
return the nums
}
i get {1,2,3,4,5}
but for some reason if the number starts with a 0 then it does not work
how to make this work if the number were
int num = 02141;
thanks
EDIT: Doh... I'd completely forgotten about octal literals. That explains why the value is showing up differently. (02141 is treated as an octal literal; it's not the same value as 2141.)
However, it sounds like the OP wants to "remember" the number of leading zeroes in a number. There's no way of doing that as an integer, because it's just remembering a value. What's the difference between seeing "3" birds and seeing "0000003" birds?
If you have a number representation where the leading zeroes are important, you're not just talking about an integer quantity, which is all that an int represents.
Where are you getting your input from? It sounds like you should just be maintaining it as a string from the start.
If you always want 5 digits, that's easy to do - and your current code should do it (when amended to actually compile) - something like this:
public class Test
{
public static void main(String[] args)
{
int[] digits = getDigits(123);
for (int digit : digits)
{
System.out.print(digit); // Prints 00123
}
}
public static int[] getDigits(int value)
{
int[] ret = new int[5];
for (int i = 4; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
return ret;
}
}
Now that's hard-coded to return 5 digits. If you don't know the number of digits at compile-time, but you will know it at execution time, you could pass it into the method:
public static int[] getDigits(int value, int size)
{
int[] ret = new int[size];
for (int i = size - 1; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
// Perhaps throw an exception here if value is not 0? That would indicate
// we haven't captured the complete number
return ret;
}
What happens in your code is that 02141 is not the same as 2141; the first is octal (equivalent to 1121 decimal), while the second is 2141 decimal.
The relevant part of the Java Language Specification is JLS 3.10.1, specifically the grammar productions for DecimalNumeral and OctalNumeral.

Categories

Resources