日期:2014-05-20 浏览次数:20667 次
public class Test { public static void main(String[] args) throws Throwable { int m = -5; int n = Math.abs(m); //取负数的绝对值 byte[] b = new byte[32]; System.out.printf("--------binary of abs(%d)----------\n", m); for (int i=0; i<32; i++) { //获取绝对值的原码 b[i] = (byte)(n>>>(32-i-1) & 0x1); System.out.printf("%d", (int)b[i]); } System.out.println("\n--------negate each byte----------"); for (int i=0; i<32; i++) { //原码的各位取反 b[i] = (byte)(~b[i] & 0x1); System.out.printf("%d", (int)b[i]); } System.out.println("\n--------plus 1----------"); b[31] += 1; //取反后+1,也就是最后1位+1 for (int i=31; i>0; i--) { //然后判断是否有发生进位 if (b[i] == 2) { //发生进位 b[i] = 0; b[i-1]++; } else { //否则,退出循环,因为后面也不会再发生进位了 break; } } b[0] %= 2; //判断最高位是否越界 for (int i=0; i<32; i++) { System.out.printf("%d", (int)b[i]); } System.out.println("\n--------check----------"); System.out.println(Integer.toBinaryString(m)); //用API的结果检验转换结果 } }