I have an array of integers.I read each value using a for loop. Now i want to append the binary of each value and get the decimal of the appended binary.
eg.
array=> 01 05
binary=> 00000001 00000101
appended binary=> 0000000100000101 which gives the decimal 261.
How do i do this?
please help.
Since this is not homework, there is no need to perform the inefficient intermediary step of "converting to binary" (integers in computers are already stored in binary format!)
public class Testy {
public static void main(String[] args) {
int[] arr = new int[] { 1, 5 };
int sum = 0;
for (int i = 0; i < arr.length; i++) {
int val = arr[i];
sum = (sum << 8) + val;
}
System.out.println("final: " + sum);
}
}
And if you are going to have more than 3 integers to include, you should make sum
a long
instead of an int
, otherwise you may get overflow.
By the way, how is your for loop getting the values? If it is reading individual bytes and converting them to ints, it might make more sense to read whole shorts or ints in one go, although watch out for endianness.