public class HiwayTest1 { public static void main(String...args){
String str = "00001101";
for(int i=0;i<str.getBytes().length;i++){
System.out.println(str.getBytes()[i]);
}
byte[] buff = change(str.getBytes());
for(int i=0;i<buff.length;i++){
System.out.println(buff[i]);
}
}
//对每个字节按位取反
private static byte[] change(byte[] buff){
for(int i=0;i<buff.length;i++){
int b = 0;
for(int j=0;j<8;j++){
int bit = (buff[i]>>j & 1) == 0?1:0;
b+=(1<<j)*bit;
}
buff[i] = (byte)b;
}
return buff;
}
}打印的结果是:
48
48
48
48
49
49
48
49
-49
-49
-49
-49
-50
-50
-49
-50
感觉这结果不对啊,还有 看不出change()方法到底是什么意思?有谁可以提供下好的取反方法?

解决方案 »

  1.   


    public static void main(String[] args) {
    String str = "00001101";
    char[] charArray = str.toCharArray();
    StringBuffer sb=new StringBuffer();
    for(char c:charArray){
    char tmp=(c=='0')?'1':'0';
    sb.append(tmp);
    }
    System.out.println(sb.toString());
    }
      

  2.   

    System.out.println(11111111-Integer.parseInt("00000101"));
      

  3.   

    对第一位为1的可能有点问题  就是一个思路 
    对一个数为取反  其实就是 
     y = 1 - x   当x = 0 => y = 1;  当x = 1 =〉  y =0 ;
    也就是取反