tags:

views:

247

answers:

4

hi, i know of several general formulas for converting between binary, decimal, and octal, but i was wondering if java has any built-in methods or classes that convert between the three. for instance, in the Integer class, there are static methods such as toBinaryString, toOctalString, etc which allow for decimal conversion, but i haven't found any to convert the other way. anyone know of anything?

in particular, i am looking for methods to convert from octal and binary to decimal and between octal and binary

thanks! x

A: 

How about: parseInt(String s, int radix)

parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
toolkit
+1  A: 

Integer.parseInt takes an optional second parameter for the base to parse it in. So to get binary,

Integer.parseInt(value, 2);

Octal,

Integer.parseInt(value,8);
Brian Schroth
+1  A: 

You're looking for Integer.parseInt(String s, int radix) and Integer.toBinaryString(int i), Integer.toOctalString(int i) and Integer.toHexString(int i). All of those are static method of the Integer class.

So to turn F hex into 1111 binary:

int fifteen = Integer.parseInt("F", 16);
String fifteenInBinary = Integer.toBinaryString(fifteen);

fifteenInBinary would equal "1111";

Kaleb Brasee
A: 

i came across that but was under the impression that it was only to decimal. for instance, how would it know that "110101" was binary not decimal? since it could be either technically...maybe i am just over thinking this?

thanks! x

dj
Er, just so you know, this isn't a discussion board, so you shouldn't post "answers" that are actually replies to other people's answers. Instead, consider editing your question to reflect new information and new questions you have in the same topic.
jprete
sorry, new here...
dj