1

Currently I have a 8 bit binary string and I want to shift it left and get a 10bit binary number from it. (ie 0111001010)

 String[] channels = datArray.get(n).split(" ");
 byte[] RI = channels[m+1].getBytes();
 String s = (Integer.toBinaryString(Integer.parseInt(channels[m+1])));

Example Values:

RI is equal to: [B@4223b758

S is equal to: 1100101

Any help is much appreciated.

Gabe Sechan
  • 77,740
  • 9
  • 79
  • 113
David Flanagan
  • 353
  • 2
  • 7
  • 19
  • 5
    `[B@4223b758` is a useless description (it's just the memory address of the object). Show the contents of the array. – nneonneo Mar 13 '13 at 17:55

2 Answers2

2

You can use following:

BigInteger i = new BigInteger("00000011" + "00", 2);
int x = i.intValue(); 

Where "00000011" is your string representation of 8 bit number. The "00" simulates the left shifting..

Akhilesh Singh
  • 2,330
  • 1
  • 11
  • 10
2

Wouldn't this work for you:

String input = "1100101";
int value = Integer.parseInt(input, 2) << 1;
System.out.println(Integer.toBinaryString(value));

Returns:

11001010

Parsed binary string and shifted left (one digit).

The two things that it looks like you are missing from your approach are the ability to specify a radix when parsing a String representing a binary numeral, and the left shift operator.

If you wanted the leading zeros I was surprised to see that there is no built in way to accomplish this, and the current wisdom is this is the optimal way (taken from this discussion)

System.out.println(String.format("%10s", Integer.toBinaryString(value)).replace(' ', '0'));

Which for the example value given would return this:

0011001010
Community
  • 1
  • 1
Jason Sperske
  • 27,420
  • 8
  • 63
  • 116
  • I can see how my answer isn't that much different than @AkhileshSingh's but I think simulating bit shift operators is less clean. To each their own :) – Jason Sperske Mar 13 '13 at 18:17