binary string to integer?

C

Christophe Vanfleteren

Daqian said:
Hi,

string s = "1001";

we I convert s to an integer? thanks.

This kind of beginners question is better suited for comp.lang.java.help.

But to answer your question, you can use the Integer.parseInt(String)
method.
 
C

Christophe Vanfleteren

Chris said:
//Try this to get a static int
static int number = Integer.parseInt(s);

//or this for non-static
int number = Integer.getInteger(s).intValue();

Excuse me? What difference does it make wether the variable you're assigning
the result to is static or not?

In both cases, you're calling a static method of the Integer class. The only
difference is that the second version returns an Integer (which you're
converting right back to an int), while the first returns the int
immediately.

So unless you actually need an Integer, use the first version.
 
D

Daqian Yang

sorry, the question may not be clear.

Let's say:

String s = "1001";

now I want an integer which is 9 which is 1001 based 2.
 
C

Christophe Vanfleteren

Daqian said:
sorry, the question may not be clear.

Let's say:

String s = "1001";

now I want an integer which is 9 which is 1001 based 2.

Have you tried Barry's answer?

int value = Integer.parseInt("1001", 2);  // 2 for binary

will do just fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top