o metodo:
Integer.parseInt(“00100”, 2) retornaria 4
Integer.parseInt(“11100”, 2) retornaria 28, e não -4.
tem algum metodo que faça essa conversão tanto para binario positivo, com binario negativo.
o metodo:
Integer.parseInt(“00100”, 2) retornaria 4
Integer.parseInt(“11100”, 2) retornaria 28, e não -4.
tem algum metodo que faça essa conversão tanto para binario positivo, com binario negativo.
Estamos falando sobre inteiros sinalizados de 32 bits de largura, portanto 11100 sempre será 28, -4 sempre será uma palavra cheia (todos os bits ligados, exceto os 2 primeiros, right most bits).
Talvez o q vc queira fazer é converter uma representação binária em um número decimal na sua forma negativa, sendo que a representação binária esteja positiva, vc pode fazer assim :
private int binary2decimal( String binStr , boolean negative ) {
int result = Integer.parseInt(binStr, 2);
return (result > 0 && negative) ? ~--result : result;
}
binary2decimal( "100", false ); // retorna 4
binary2decimal( "100", true ); // retorna -4
binary2decimal( "11100", false ); // retorna 28
binary2decimal( "11100", true ); // retorna -28
eu fiz esse codigo. Ele faz assim, se a String começar com 0 elejá converte automaticamente para inteiro, se não ele faz o complemento de 1, ou seja onde tem 0 ele coloca 1, e depois faz o complemento 2 somando com 1, e negando dpois para ficar negativo como esperado.
private int binarioComplemento(String s){
StringBuffer buf = new StringBuffer(s);
if(buf.charAt(0) == '0')
return Integer.parseInt(s, 2);
else{
for(int i = 0; i < s.length(); i++)
if(buf.charAt(i) == '0')
buf.setCharAt(i, '1');
else
buf.setCharAt(i, '0');
int bin = Integer.parseInt(buf.toString(), 2);
return -(++bin);
}
}
Do jeito q vc fez nõ da certo para o q quero. valewwwws.