Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Java) Specify number of bits (length) when converting binary number to string?

Tags:

java

binary

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.

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

Can anyone help?

EDIT: 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.

like image 221
joinJpegs Avatar asked Mar 09 '09 11:03

joinJpegs


People also ask

How do you convert a number to a binary string?

toBinaryString(int i) To convert an integer to binary, we can simply call the public static String toBinaryString(int i) method of the Integer class. This method returns the binary string that corresponds to the integer passed as an argument to this function.

Which Java method is used to convert an integer into a binary string?

Java's Integer class has a method named toBinaryString to convert an integer into its binary equivalent string.

How do you find the length of a binary number?

The length of a binary number is given by the value of n, actually it's n+1. For example, a binary number like 101 has a length of 3, something larger, like 10011110 has a length of 8.

How does Java calculate binary representation of a number?

To convert decimal to binary, Java has a method “Integer. toBinaryString()”. The method returns a string representation of the integer argument as an unsigned integer in base 2.


1 Answers

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

like image 100
David Z Avatar answered Nov 05 '22 11:11

David Z