在Java中的二进制转换程序之后,我如何将二进制的格式化为4位?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
让我们扔一些 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 进入我们的解决方案以完成学习练习。
流 /收集器 /正则解决方案:
输出:
Let's throw some Streams, Collectors and RegEx into our solution to complete the learning exercise.
Stream / Collector / RegEx solution:
Output:
一次取4位,然后打印碎片。
使用递归实现以正确的顺序打印nibbles。
给定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.
Given 291 (which is 0x123) the output is
0001.0010.0011
您可以制作自己的tobinarystring方法。但是首先,您必须了解&lt;&lt;运营商,它基本上将二进制数字转移到左侧,而您给它的值。
示例:
现在您可能会问这是什么用法?好吧,您可以在Shift Operator的帮助下制作自己的Tobinary String方法,以完成您想做的事情,
但是在跳到代码之前,您必须知道如何&amp;操作员工作:
1000&amp; 0001 = 0,
假设您将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:
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
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
原始方法:
Primitive approach: