Fog Creek Software
Discussion Board




convert an integer to a binary string in Java?

Any API calls to do this?

SR
Friday, January 23, 2004

The Integer class can do it.

Mike Swieton
Friday, January 23, 2004

Yeah, you might find the Java API's to be really poorly documented.

Jimmy Jo-jo
Saturday, January 24, 2004

java.io.DataOutputStream

Mike
Saturday, January 24, 2004

Hi,

String s = Integer.toBinaryString(n);

The returned String is not padded to 32 places, however; all leading "0"s are dropped.

SG
Saturday, January 24, 2004



public static String valueOf(int i)
Returns the string representation of the int argument.

The representation is exactly the one returned by the Integer.toString method of one argument.

so you do something like:
int x = 10;
String foo = String.valueOf(x);

bar
Saturday, January 24, 2004

String.valueOf(n) returns a base-10, 2's complement String representation of its argument, not a binary String representation. In other words:

String.valueOf(-1) ---> "-1"
Integer.toBinaryString(-1) --> "11111111111111111111111111111111"

SG
Sunday, January 25, 2004

I've always wondered this, but is there a way to turn on a flag for Java/C# to have it implicitly convert to a string when I'm either doing message boxes, text fields, etc.

Why do I have to do (C#):
MessageBox.Show( someInt.ToString( ) );
someTextBox.text = someInt.ToString( );
System.Out.PrintLine( someInt.ToString( ) );

That just seems silly.

MR
Monday, January 26, 2004

In C++ you could do it by defining a conversion operator for into to string (your conversion operator could be implemented using the the ToString method).

A reason why you wouldn't do this is that converting int to string isn't what you always want to be doing (so doing it automatically gets rid of compiler-enforced type safety): the kind of srgument that made STL designers define string::c_str() as a method to be called explicitly, instead of as an operator to be called implicitly.

Christopher Wells
Monday, January 26, 2004

---------------------------
I've always wondered this, but is there a way to turn on a flag for Java/C# to have it implicitly convert to a string when I'm either doing message boxes, text fields, etc.
---------------------------
The easiest way, IMO, in both Java and C# is to use String concatenation like this:

int n = 3; // number to be converted
tf.setText("" + n);

SG
Monday, January 26, 2004

*  Recent Topics

*  Fog Creek Home