2013-03-13 29 views
1

目前我有一個8位的二進制字符串,我想將它左移並從中得到一個10位的二進制數。 (即0111001010)從一個字符串到一個字節的10bit二進制數

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

示例值:

RI等於:[B @ 4223b758

S等於:1100101

任何幫助十分讚賞。

+5

'[B @ 4223b758'是一個沒用的描述(它只是對象的內存地址)。顯示數組的內容。 – nneonneo 2013-03-13 17:55:40

回答

2

這是不是對你的工作:

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

返回:

11001010 

分析二進制字符串,並向左移動(個位數)。

你看起來像缺少的兩件事情是在解析代表二進制數字的字符串時的specify a radixleft shift operator的能力。

如果你想前導零我很驚訝地看到,沒有內置的方法來做到這一點,而目前的看法是,這是最佳的方式(從this discussion拍攝)

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

這對於給出的示例值將返回:

0011001010 
+0

我可以看到我的答案與@AkhileshSingh的答案沒有太大區別,但我認爲模擬位移操作符不太清晰。給每個人自己:) – 2013-03-13 18:17:02

2

您可以使用下面:

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

其中, 「00000011」 是8位數字的字符串表示。在 「00」 模擬左移..

+0

似乎很多工作都是爲了避免使用['<<'](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html) – 2013-03-13 18:02:46

+0

其實沒有。如果我們注意到問題始於字符串輸入而不是數字類型。如果我們必須解析字符串,BigInteger不會有很多工作。 – 2013-03-13 18:07:04

相關問題