废话不多说:直接上代码:
public
static
int
binaryToInt(String binary) {
if
(binary ==
null
) {
System.
out
.println(
"can't input null !"
);
}
if
(binary.isEmpty()) {
System.
out
.println(
"you input is Empty !"
);
}
int
max = binary.length();
String new_binary =
""
;
if
(max >= 2 && binary.startsWith(
"0"
)) {
int
position = 0;
for
(
int
i = 0; i < binary.length(); i++) {
char
a = binary.charAt(i);
if
(a !=
'0'
) {
position = i;
break
;
}
}
if
(position == 0) {
new_binary = binary.substring(max - 1, max);
}
else
{
new_binary = binary.substring(position, max);
}
}
else
{
new_binary = binary;
}
int
new_width = new_binary.length();
long
result = 0;
if
(new_width < 32) {
for
(
int
i = new_width; i > 0; i--) {
char
c = new_binary.charAt(i - 1);
int
algorism = c -
'0'
;
result += Math. pow(2, new_width - i) * algorism;
}
}
else
if
(new_width == 32) {
for
(
int
i = new_width; i > 1; i--) {
char
c = new_binary.charAt(i - 1);
int
algorism = c -
'0'
;
result += Math. pow(2, new_width - i) * algorism;
}
result += -2147483648;
}
int
a =
new
Long(result).intValue();
return
a;
}
同时附上java中int转成二进制String类型的方法:
int num;
String str = Integer.toBinaryString(num);