(Java)将二进制数转换为字符串时指定位数(长度)?

(Java) Specify number of bits (length) when converting binary number to string?((Java)将二进制数转换为字符串时指定位数(长度)?)
本文介绍了(Java)将二进制数转换为字符串时指定位数(长度)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试将数字作为二进制字符串存储在数组中,但我需要指定将其存储为多少位.

I'm trying to store a number as a binary string in an array but I need to specify how many bits to store it as.

例如,如果我需要用两位存储 0,我需要一个字符串00".或者 1010 有 6 位所以001010".

For example, if I need to store 0 with two bits I need a string "00". Or 1010 with 6 bits so "001010".

谁能帮忙?

谢谢大家,因为我一般在数学/编程方面都很垃圾,所以我选择了最简单的解决方案,即 David 的解决方案.比如:

Thanks guys, as I'm rubbish at maths/programming in general I've gone with the simplest solution which was David's. Something like:

binaryString.append(Integer.toBinaryString(binaryNumber));
for(int n=binaryString.length(); n<numberOfBits; n++) {
                        binaryString.insert(0, "0");
}

它似乎工作得很好,所以除非它效率很低,否则我会用它.

It seems to work fine, so unless it's very inefficient I'll go with it.

推荐答案

使用 Integer.toBinaryString() 然后检查字符串长度并在其前面添加尽可能多的零以达到所需长度.

Use Integer.toBinaryString() then check the string length and prepend it with as many zeros as you need to make your desired length.

这篇关于(Java)将二进制数转换为字符串时指定位数(长度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)