gpt4 book ai didi

java - 将 int 转换为带有额外内容的 32 位二进制行

转载 作者:行者123 更新时间:2023-11-29 04:59:41 25 4
gpt4 key购买 nike

用户输入一个 8 个字符的字符串,然后将其转换为字符串并放入数组中进行播放。

有了这 8 位数字,我希望能够将它们转换成 32 位二进制例如

  • 0000 0000 0000 0000 0000 0000 0000 0000

整数 = 12,345,678

  • 0000 0000 1011 1100 0110 0001 0100 1110

整数 = -10,000,000

  • 1111 1111 0110 0111 0110 1001 1000 0000

     System.out.print("Please enter an 8 digit number");
    System.out.println();
    Scanner user_input = new Scanner( System.in );
    StudentID = user_input.nextLine();
    sID = Integer.parseInt(StudentID);
    String ss[] = StudentID.split("");
    StudentID = Integer.toBinaryString(sID);

    while(loop >= 0){
    d[loop] = Integer.parseInt(ss[loop]) ;
    loop--;
    }

我试过使用“StudentID = Integer.toBinaryString(sID);”然而,它不会产生加法 0 来组成 32 位(可能更有效)。像这样

  • 101111000110000101001110

我如何才能允许所有整数显示在 32 位字符串中,以及接受负数(我可以使用两个补码的取反)?

很棒的引用; http://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html

最佳答案

对于整数,你可以使用这个技巧:

String result = Long.toBinaryString( sID & 0xffffffffL | 0x100000000L ).substring(1);

这会将整数放入 long 中,在其左侧添加一位,这意味着 toBinaryString 将具有 33 位数字,然后取右侧32 位数字(删除添加的额外 1)。

Java 8 版本:

String result = Long.toBinaryString( Integer.toUnsignedLong(sID) | 0x100000000L ).substring(1);

关于java - 将 int 转换为带有额外内容的 32 位二进制行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32488023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com