Question
Write a method binaryToDecimal that converts a given binary String (base 2) into a decimal value (base 10). For example binaryToDecimal(1101); Should return 13 Because
Write a method binaryToDecimal that converts a given binary String (base 2) into a decimal value (base 10).
For example
binaryToDecimal("1101");
Should return
13
Because the binary value 11012 is equal to the decimal value 1310 This value can be computed by multiplying each bit by the value of its place:
Bits: 1 1 0 1 Place: 2^3 2^2 2^1 2^0 Place value: 8 4 2 1 Compute decimal value: 1*(8) + 1*(4) + 0*(2) + 1*(1) = 13
You may assume that the method will only be passed valid binary Strings (only 0s and 1s)
HINT: You may find it useful to look at the OctalToDecimal program in the previous example. This problem is very similar, only you need to convert from base 2 instead of base 8.
Sample Code:
/* Convert a given binary string * into the equivalent decimal value. * returns an int representing the decimal value * of the binary string * * Ex: "1101" * * Bits: 1 1 0 1 * * Place: 2^3 2^2 2^1 2^0 * * Place value: 8 4 2 1 * * Compute decimal value: 1*(8) + 1*(4) + 0*(2) + 1*(1) = 13 */ public int binaryToDecimal(String binaryString) { // Write your code here! return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started