David Flanagan
David Flanagan

Reputation: 373

10bit binary number from a string to a byte

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.

Upvotes: 1

Views: 773

Answers (2)

Jason Sperske
Jason Sperske

Reputation: 30416

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

Upvotes: 2

Akhilesh Singh
Akhilesh Singh

Reputation: 2586

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..

Upvotes: 2

Related Questions