問題描述
我正在嘗試將數字作為二進制字符串存儲在數組中,但我需要指定將其存儲為多少位.
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)將二進制數轉換為字符串時指定位數(長度)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!