当前位置:网站首页>Integer to 8-bit binary explanation (including positive and negative numbers) scope of application -127~+127

Integer to 8-bit binary explanation (including positive and negative numbers) scope of application -127~+127

2022-07-05 06:35:00 Said it was all

Look directly at the code , There are notes , What's wrong, please correct , The first bit of binary is sign bit :

public class TheTwoTogether {
    
    public static void main(String[] args) {
    
        // Convert string to binary number 
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        if (a < 0) {
    
           String s1[] =eightbinary(a);
            s1[0]="1";
            for (String s:s1){
    
                System.out.print(s);
            }
         }
        else {
    
            String s1[] =eightbinary(a);
            for (String s:s1){
    
                System.out.print(s);
            }
        }
    }
        private static  String[] eightbinary(int a){
    
            int b = Math.abs(a);// Take the absolute value 
            String s = Integer.toBinaryString(b);
            // The next step is for : Will be for Integer Class binary conversion to 8 Bit Integer Class binary . because %08d Medium d It is not required to be an integer type 
            Integer s2=Integer.valueOf(s);
            // Will be for Integer Class binary conversion to 8 Bit Integer Class binary ( Probably not 8 position , such as  3---->11, Namely 2 position )
            String sb1 = String.format("%08d", s2);
            int arr[] = new int[8];
            // Separate eight binary bits , One by one , Deposit to string An array of types sarray in 
            String[] sarray = sb1.split("");
            return  sarray;
    }
}

The scope of application of this code -127~+127, The reason is that the limitation of my transformation is 8 Bit binary , And the first bit is the sign bit , If you want to expand the scope , Change it to hexadecimal or 32nd , The way of thinking remains unchanged .

原网站

版权声明
本文为[Said it was all]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140603261460.html