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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!