java整数int的32位输出

本文介绍了如何使用Java将32位整数转换为二进制字符串,重点讲解了正负数的处理方法,并通过示例展示了在主函数中的应用。理解这个技巧对于理解和处理计算机底层数据表示至关重要。
    /**
     * Integer.toBinaryString 32位二进制表示
     * int一共8个字节即32位
     * 最高位是符号位 从2的0次开始
     * 正数范围:2^31-1  2147483647
     * 负数范围:-2^31  -2147483648
     * 本身toBinaryString函数,输出负数是32位的
     */
    public static String intToBinary32(int num) {
        String binaryStr = Integer.toBinaryString(num);
        if(num >= 0){ //负数直接返回就行
            while (binaryStr.length() < 32) {
                binaryStr = "0" + binaryStr;
            }
        }
        return binaryStr;
    }

    public static void main(String[] args) {
        System.out.println(intToBinary32(-2));
        System.out.println(intToBinary32(2));
    }

输出:

11111111111111111111111111111110
00000000000000000000000000000010

 

 

 

 

Java中,输出整数有多种方法,以下结合参考内容介绍几种常见方式: ### 直接输出整数 可以使用`System.out.print()`或`System.out.println()`方法直接输出整数。例如,在无限制整数的逆序输出代码中,使用`System.out.print()`输出每一数字: ```java import java.util.Scanner; class Cycle01 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("输入一个整数:"); int num = input.nextInt(); while (num!=0) { System.out.print(num % 10); num /= 10; } } } ``` 这里`System.out.print(num % 10)`用于逐个输出整数的每一数字。如果要换行输出,可以使用`System.out.println()`。 ### 格式化输出整数 使用`System.out.printf()`方法可以对整数进行格式化输出。如在Java逆序输出整数代码中,使用`System.out.printf()`输出逆序后的整数: ```java import java.util.Scanner; public class Test { static int reverseDigit(int n) { int result = n, count = 1; while ((result /= 10) != 0) { count++; } int[] list = new int[count]; result = 0; for (int i = 0; i < count; i++) { list[i] = n % 10; result += list[i] * Math.pow(10, count - 1 - i); n = n / 10; } return result; } public static void main(String[] args) { int n; System.out.println("Please input a int:"); Scanner sc = new Scanner(System.in); n = sc.nextInt(); System.out.printf("The reverse is %d !\n", reverseDigit(n)); sc.close(); } } ``` 其中`System.out.printf("The reverse is %d !\n", reverseDigit(n));`使用`%d`作为整数的占符,将逆序后的整数格式化输出。 ### 数组形式输出整数 可以将整数的每一存放在数组中,然后遍历数组输出。在整数逆序输出几种方法小结(Java实现)代码中,将整数的每一存放在数组中并输出: ```java import java.util.Scanner; public class tter { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.next(); int[] resu = new int[str.length()]; int temp, i = 0; int res = Integer.parseInt(str); for (i = 0; i < str.length(); i++) { temp = res % 10; resu[i] = temp; res = res / 10; } for (i = 0; i < str.length(); i++) { if(resu[i]==0){ continue; } System.out.print(resu[i]); } } } ``` 这里将整数的每一存放在`resu`数组中,然后遍历数组输出每一数字。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值