在Java中的二进制转换程序之后,我如何将二进制的格式化为4位?

发布于 2025-01-29 07:26:19 字数 414 浏览 1 评论 0原文

import java.util.*;

public class Binary {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        int number = input.nextInt();
        String binary = Integer.toBinaryString(number);
        System.out.println(binary);

    }

}

我正在尝试创建一个程序,该程序将整数转换为二进制,每四个位每四个部分组。例如,如果我输入1,我想获得0001,但我得到1

import java.util.*;

public class Binary {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);

        int number = input.nextInt();
        String binary = Integer.toBinaryString(number);
        System.out.println(binary);

    }

}

I am trying to create a program which converts an integer into binary and groups every four bits. For example, if I input 1, I want to get 0001, but I get 1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

地狱即天堂 2025-02-05 07:26:19

让我们扔一些 streams ,,,,< a href =“ https://docs.oracle.com/javase/8/docs/api/java/java/java/util/stream/collectors.html” rel =“ nofollow noreferrer”> collectors> collectors> https://stackoverflow.com/a/40375117/5046445"> regex 进入我们的解决方案以完成学习练习。

流 /收集器 /正则解决方案:

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

class Binary
{
  public static void main( String[] args )
  {
    Scanner input = new Scanner( System.in );
    int number = input.nextInt();
    String binary = Integer.toBinaryString( number );
    System.out.println( binary );

    // SOLUTION:
    int digitsInGroup = 4;
    String separator = ".";
    while( binary.length() % digitsInGroup > 0 )
      binary = "0" + binary;
    binary = Arrays.stream( binary.split( String.format( "(?<=\\G.{%d})", digitsInGroup ) ) ).collect( Collectors.joining( separator ) );
    System.out.println( binary );
  }
}

输出:

> java Binary.java
1
1
0001

> java Binary.java
16
10000
0001.0000

> java Binary.java
31000
111100100011000
0111.1001.0001.1000

Let's throw some Streams, Collectors and RegEx into our solution to complete the learning exercise.

Stream / Collector / RegEx solution:

import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;

class Binary
{
  public static void main( String[] args )
  {
    Scanner input = new Scanner( System.in );
    int number = input.nextInt();
    String binary = Integer.toBinaryString( number );
    System.out.println( binary );

    // SOLUTION:
    int digitsInGroup = 4;
    String separator = ".";
    while( binary.length() % digitsInGroup > 0 )
      binary = "0" + binary;
    binary = Arrays.stream( binary.split( String.format( "(?<=\\G.{%d})", digitsInGroup ) ) ).collect( Collectors.joining( separator ) );
    System.out.println( binary );
  }
}

Output:

> java Binary.java
1
1
0001

> java Binary.java
16
10000
0001.0000

> java Binary.java
31000
111100100011000
0111.1001.0001.1000
删除会话 2025-02-05 07:26:19

一次取4位,然后打印碎片。

使用递归实现以正确的顺序打印nibbles。

public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   printbin(input.nextInt());
}

static void printbin(int number) {
    int lo = number & 15;
    int hi = number >>> 4;
    if (hi != 0) {
        printbin(hi);
        System.out.print('.');
    }
    for (int n=3; n>=0; n--) {
        System.out.print((lo >> n) & 1);
    }
}

给定291(是0x123)输出为
0001.0010.0011

Take the number 4 bits at a time, and print the bits.

Use a recursive implementation to get the nibbles printed in the correct order.

public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
   printbin(input.nextInt());
}

static void printbin(int number) {
    int lo = number & 15;
    int hi = number >>> 4;
    if (hi != 0) {
        printbin(hi);
        System.out.print('.');
    }
    for (int n=3; n>=0; n--) {
        System.out.print((lo >> n) & 1);
    }
}

Given 291 (which is 0x123) the output is
0001.0010.0011

一绘本一梦想 2025-02-05 07:26:19

您可以制作自己的tobinarystring方法。但是首先,您必须了解&lt;&lt;运营商,它基本上将二进制数字转移到左侧,而您给它的值。
示例:

int n = 1; // 0001
n = ( n<<(4-1) ); // shift the binary number of 1 to the left 3 times
System.out.println(toBinaryString(n)); // = 1000;

现在您可能会问这是什么用法?好吧,您可以在Shift Operator的帮助下制作自己的Tobinary String方法,以完成您想做的事情,

但是在跳到代码之前,您必须知道如何&amp;操作员工作:
1000&amp; 0001 = 0,

public static String toBinaryString(int n) {
    String binary = ""; //Start with an empty String

    // int i in binary = 1000, as long as i > 0, divide by 2
    for (int i = (1 << (4 - 1)); i > 0; i /= 2) {

        // if binary n & i are NOT 0, add 1 to the String binary, Otherwise add 0
        binary += (n & i) != 0 ? "1" : "0";
    }
    return binary;
}

假设您将1个输入放置:

tobinarystring(1); // 1 = 0001在二进制

函数中启动:

i 以二进制值为1000,等于int 8
8大于0吗?是的,除以2
8/2 = 4;
4在二进制中为00100,现在让我们将其与我们的输入0001

00100&amp; 进行比较。 0001 = 0? //是

添加0到字符串二进制。

现在将4除以2,然后重复循环。该函数将在末尾添加3个零和1。那将是您的0001。

在循环的末尾,二进制文件将是您想要的字符串值。

我希望我能帮助

〜莫斯塔法

You can make your own toBinaryString method. But first you have to understand the << operator, it basically shifts binary numbers to the left by the value you give to it.
example:

int n = 1; // 0001
n = ( n<<(4-1) ); // shift the binary number of 1 to the left 3 times
System.out.println(toBinaryString(n)); // = 1000;

now you might ask what is the usage of this? well you can make your own toBinaryString method with the help of the shift operator to do what you want

but before jumping to the code you have to know how the & operator works:
1000 & 0001 = 0

public static String toBinaryString(int n) {
    String binary = ""; //Start with an empty String

    // int i in binary = 1000, as long as i > 0, divide by 2
    for (int i = (1 << (4 - 1)); i > 0; i /= 2) {

        // if binary n & i are NOT 0, add 1 to the String binary, Otherwise add 0
        binary += (n & i) != 0 ? "1" : "0";
    }
    return binary;
}

let's say you put 1 as input:

toBinaryString(1); // 1 = 0001 in binary

the function starts:

i starts at a binary value of 1000 which is equal to int 8
is 8 bigger than 0? yes, divide by 2
8/2 = 4;
4 in binary is 00100, now lets compare it with our input 0001

00100 & 0001 = 0? // YES

add 0 to String binary.

now divide 4 by 2 and repeat the loop. The function will add 3 zeros and 1 at the end. That will be your 0001.

At the end of the loop binary will be your wanted value as a String.

I hope i helped

~Mostafa

苏璃陌 2025-02-05 07:26:19

原始方法:

import java.util.*;
public class Binary {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            int number = input.nextInt();
            String binary = Integer.toBinaryString(number);
            System.out.println(binary);

            int paddingLength = (4 - binary.length() % 4) % 4;
            StringBuilder grouped = new StringBuilder();
            for (int i = 0; i < paddingLength; i++) {
                grouped.append('0');
            }
            for (int i = 0; i < binary.length(); i++) {
                if (i != 0 && (i + paddingLength) % 4 == 0) {
                    grouped.append('.');
                }
                grouped.append(binary.charAt(i));
            }
            System.out.println(grouped);
        }
    }
}
$ java Binary.java
1
1
0001
$ java Binary.java
16
10000
0001.0000
$ 

Primitive approach:

import java.util.*;
public class Binary {
    public static void main(String[] args) {
        try (Scanner input = new Scanner(System.in)) {
            int number = input.nextInt();
            String binary = Integer.toBinaryString(number);
            System.out.println(binary);

            int paddingLength = (4 - binary.length() % 4) % 4;
            StringBuilder grouped = new StringBuilder();
            for (int i = 0; i < paddingLength; i++) {
                grouped.append('0');
            }
            for (int i = 0; i < binary.length(); i++) {
                if (i != 0 && (i + paddingLength) % 4 == 0) {
                    grouped.append('.');
                }
                grouped.append(binary.charAt(i));
            }
            System.out.println(grouped);
        }
    }
}
$ java Binary.java
1
1
0001
$ java Binary.java
16
10000
0001.0000
$ 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文