java原码补码反码关系解析
本文为大家解析了java原码补码反码的关系,供大家参考,具体内容如下
原码:不管源数据是十进制还是十六进制,统统将数字转成二进制形式
反码:把原码的二进制统统反过来,0变成1,1变成0
补码:负数的反码加1,就是负数的补码
例子1:
十进制整数 -5,-5的原码101,-5的反码1,010,-5的补码1,011,
所以,-5的反码是-2,-5的补码是-3,其中前面的"1,",表示正数负数
例子2:
十六进制 -ff9B
原码 11111111111110011011
反码 00000000000001100100 十进制100
补码 00000000000001100100 十进制101
原来正确的操作流程是,把16进制ff9B转成2进制,然后直接反码,再算补码,就是温度数据
代码验证:
package comtest.example.admin.znum; /** * Created by wrs on 2019/6/5,16:25 * projectName: Testz * packageName: comtest.example.admin.znum * 输入一个真值(整数)求它的原码,反码,补码 */ import java.util.Scanner; public class Test { public static void main(String[] args) { System.out.println("True value--> original code"); System.out.println("Please enter an integer!!!!!"); Scanner sc = new Scanner(System.in); int value = sc.nextInt(); StringBuilder syuan = new StringBuilder(); if (value > 0) { String Bvalue = Integer.toBinaryString(value);//将一个整数转换成字符串类型的二进制数 int n = Bvalue.length(); //二进制的数字的个数n syuan.append("0,"); syuan.append(Bvalue); System.out.println("Original code " + syuan); //原码 System.out.println("Complement code " + syuan); //补码 System.out.println("Inverse code " + syuan); //反码 // System.out.println("二进制数的n "+n); } else if (value < 0) { int value2 = Math.abs(value); //负数的绝对值 int value3 = value2 - 1; //减一求反,求补码 String Bvalue = Integer.toBinaryString(value2); String BFvalue = Integer.toBinaryString(~value2); int n = Bvalue.length(); String str = BFvalue.substring(BFvalue.length() - n); //截取反码的后几个数 syuan.append("1,"); syuan.append(Bvalue); System.out.println("Original code is :" + syuan); System.out.println("Inverse code is :1," + str); String BBvalue = Integer.toBinaryString(~value3); String str3 = BBvalue.substring(BFvalue.length() - n); System.out.println("Complement code is :1," + str3); } else { System.out.println("0 Original code is not only"); System.out.println("[+0]riginal code 00.....0"); System.out.println("[-0]riginal code 10.....0"); System.out.println("--------------------------------------------"); System.out.println("0 Complement code is not only"); System.out.println("[+0]和[-0] Complement code 00.....0"); System.out.println("---------------------------------------------"); System.out.println("0 Inverse code is not only"); System.out.println("[+0]Inverse code00..........0"); System.out.println("[-0]Inverse code11..........1"); } System.out.println("-------------------------------------------------"); } }
运行效果:
------------------------------------------------- True value--> original code Please enter an integer!!!!! -65435 Original code is :1,1111111110011011 Inverse code is :1,0000000001100100 Complement code is :1,0000000001100101 -------------------------------------------------
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)