计算机基础01

95 阅读1分钟

二进制表示整数

public static String transferBy32(int num) {
	StringBuilder sb = new StringBuilder();
	for (int w = 31; w >= 0; w--) {
		sb.append((num & (1 << w)) == 0 ? "0" : "1");
	}
	return sb.toString();
}

负数的表示方式为源数字取反+1

验证如下:

public static void main(String[] args) {
	System.out.println(transferBy32(1));
	System.out.println(transferBy32(2));
	System.out.println(transferBy32(3));
	System.out.println(transferBy32(~3 + 1));
	System.out.println(transferBy32(-3));
}

输出结果:

00000000000000000000000000000001
00000000000000000000000000000010
00000000000000000000000000000011
11111111111111111111111111111101
11111111111111111111111111111101