How to convert a Binary String to a base 10 integer in Java
You need to specify the radix. There's an overload of Integer#parseInt()
which allows you to.
int foo = Integer.parseInt("1001", 2);
Converting binary to base 10 without math.pow( )?
I'd work backwards from the end of the string and just calculate the power for each character incrementally:
public static int binaryToNumber (String numberInput) {
int currentPower = 1;
int total = 0;
for (int i = numberInput.length() - 1; i >= 0; i--) {
if (numberInput.charAt(i) == '1') {
total += currentPower;
}
currentPower *= 2;
}
return total;
}
How to convert a binary String to a decimal string in Java
To convert a base 2 (binary) representation to base 10 (decimal), multiply the value of each bit with 2^(bit position) and sum the values.
e.g. 1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11
Since binary is read from right-to-left (i.e. LSB (least significant bit) is on the rightmost bit and MSB (most-significant-bit) is the leftmost bit), we traverse the string in reverse order.
To get the bit value, subtract '0' from the char. This will subtract the ascii value of the character with the ascii value of '0', giving you the integer value of the bit.
To calculate 2^(bit position), we can keep a count of the bit position, and increment the count on each iteration. Then we can just do 1 << count to obtain the value for 2 ^ (bit position). Alternatively, you could do Math.pow(2, count) as well, but the former is more efficient, since its just a shift-left instruction.
Here's the code that implements the above:
public static int convertBinStrToInt(String binStr) {
int dec = 0, count = 0;
for (int i = binStr.length()-1; i >=0; i--) {
dec += (binStr.charAt(i) - '0') * (1 << count++);
}
return dec;
}
Converting numbers in string to base 10 number
You're calculating your powers in the wrong order, giving the highest weight to the last digit rather than the first.
In fact, you don't need to calculate the power for each digit; instead you can multiply your accumulator directly:
for(int i = 0; i<s.length(); i++){
char cur = s.charAt(i);
if(base >= 0 && base <= 9){
ret = ret * base + (cur - '0');
}
}
Doing it this way works just the same as when you write a number on paper. If you write "10", and then you write another digit after that then the value becomes ten times greater (or two times, or whatever your base is). You add another digit and it gets ten (or two, or whatever) times greater again.
The only reason we have to think about tens and hundreds and thousands columns directly is when we read a decimal number aloud and we have to use the right words.
java: convert binary string to int
From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) : the toBinaryString()
method converts its input into the binary representation of the "unsigned integer value is the argument plus 232 if the argument is negative".
From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) : the parseInt()
method throws NumberFormatException
if "The value represented by the string is not a value of type int
".
Note that both ~0
and ~1
are negative (-1 and -2 respectively), so will be converted to the binary representations of 232-1 and 232-2 respectively, neither of which can be represented in a value of type int
, so causing the NumberFormatException
that you are seeing.
How to convert binary string value to decimal
Use Integer.parseInt
(see javadoc), that converts your String
to int
using base two:
int decimalValue = Integer.parseInt(c, 2);
Converting an int to a binary string representation in Java?
Integer.toBinaryString(int i)
Convert 64-Bit Binary floating-point number into a base 10 decimal
Here is the explanation. As you already stated, the main parts are:
- sign = 0
- exponent = 10000000000
- mantissa = 1001001000011111101101010100010001000010110100011000
Since all mantissa values are shifted left (normalized) until the first bit is a 1
, that bit can be implied. So the actual mantissa prefixed with a 1
, the value would be
- mantissa = 11001001000011111101101010100010001000010110100011000
The base offset for the exponent is 1023
. The exponent above is 1024
so the exponent would be 1
+ an additional 1
for the implied bit.
.11 x 2
2
So the whole number part would be binary 11
or decimal 3
.
double whole = 3;
The rest of the mantissa is the fractional part and starts where the whole number stopped.
fraction = 001001000011111101101010100010001000010110100011000
so given a string of bits as above, the fractional part can be added to the whole by dividing each successive bit by ever increasing powers of 2. (e.g. 0/2 + 0/4 + 1/8 + etc)
double div = 1.;
for (char c : fract.toCharArray()) {
div*=2.;
whole += (c-'0')/div;
}
System.out.println(whole);
prints
3.141592653589793
Note: The above was cheating somewhat in that it used a double to compute the fractional part. There are more involved methods to emulate floating point math but the purpose here was to demonstrate extracting the bit fields to create a double value. If I were doing this I would use the methods described in the other answers.
Related Topics
How to Set Java Max Heap Size for Running from a Jar File
Is -Djava.Library.Path=... Equivalent to System.Setproperty("Java.Library.Path", ...)
Java Error: Cannot Make a Static Reference to the Non-Static Method
Find Duplicate Element in Array in Time O(N)
Invalid Syntax Error "Type= Myisam" in Ddl Generated by Hibernate
How to Use the Jersey JSON Pojo Support
What Is the Equivalent of Java Static Final Fields in Kotlin
How to Convert a Word Document to PDF
Eclipse Will Not Open Due to Environment Variables
Difference Between Openjdk and Adoptium/Adoptopenjdk
How to Use Readline() Method in Java
Comparing Boxed Long Values 127 and 128
Why Is System.Arraycopy Native in Java
String Replacement in Java, Similar to a Velocity Template