0

How would I split a binary number up by each individual digit and then put it into a java list back to front.

For example: Binary Number:

01111101

After it is split up it would look like

int[] binary = {0,1,1,1,1,1,0,1}

After it the array is flipped it would look like

int[] binaryFlipped={1,0,1,1,1,1,1,0}

I am doing this so that I can convert a binary number into a denary number in java. So i would take the flipped list the for each binary digit work out it's denary value. This is an example of ruffle how i would do it. (Note: lengthOfList is not the write method but is just there for an example of how it would work)

For(x=0;lengthOflist(binary);x++){
    sum=binary[x]*pow(2,x)+sum;
    }
System.out.println(sum);
matt
  • 337
  • 4
  • 14

1 Answers1

3

Assuming that your input is an int and not a String:

    int number = 2;
    int[] binaryFlipped = new int[8];
    for (int i = 0; i < binaryFlipped.length; i++) {
        binaryFlipped[i] = number % 2;
        number = number >> 1;
    }
dotvav
  • 2,808
  • 15
  • 31
  • which variable is the binary number? – matt Jul 30 '15 at 09:45
  • I used `int[8]` because your example had 8 bits but an int precision in Java is 32 bits. – dotvav Jul 30 '15 at 09:47
  • There is no interim binary number in this implementation – dotvav Jul 30 '15 at 09:48
  • I get that. But which variable would I output to get the flipped binary number – matt Jul 30 '15 at 09:48
  • I suppose it is `binaryFlipped` since that is the name you used in your code :) – dotvav Jul 30 '15 at 09:51
  • You could use `number & 1` instead of `number % 2` – Reboot Jul 30 '15 at 09:51
  • Sorry it did sound stupid. But i outputed binaryFlipped using. System.out.println(binaryFlipped); and i got this: [I@659e0bfd – matt Jul 30 '15 at 09:52
  • @matt: http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array :). What you see there is the default result of the `toString` method. – Tom Jul 30 '15 at 09:53
  • If you need the denary representation of `binaryFlipped`, then I am leaving it to you as an exercise. Your question contains something that seems OK to me, but you could also try something with the binary operator `<<`. – dotvav Jul 30 '15 at 09:54
  • No I will to the converting bit by myself. However I just need to check the value of the binaryflipprd before moving on and currently that is not the expected output – matt Jul 30 '15 at 09:56
  • Just add `System.out.print(binaryFlipped[i] + " ");` at the end of the `for` loop. – dotvav Jul 30 '15 at 10:01