0

I am having a hard time figuring out the answer to a homework assignment for Programming 1 class. The assignment is prompt a user for input (up to 4 bits) in binary, and convert it to the decimal equivalent. Using loops, conditional statements, ParseInt, and anything other than the modulus operator and other math operators are not allowed.

I am having trouble with the mathematical aspect, I think once I understand how to use the modulus operator to answer the question I would be able to write the code for it.

I have searched and have not been able to find anything that was able to help.

6
  • show us some code please. Commented Aug 26, 2016 at 5:16
  • see stackoverflow.com/a/11419738/2310289 Commented Aug 26, 2016 at 5:20
  • The modulus operator is not well suited for this problem. Commented Aug 26, 2016 at 5:20
  • Shift is also not allowed, and I agree modulus operator is not best suited for this however, that is the assignment for school. This is why I am having such a difficult time with it. Commented Aug 26, 2016 at 5:22
  • Furthermore it will be hard to do this without a conditional statement or loop, if the input should be up to 4 characters. Who writes these kind on assignments? Commented Aug 26, 2016 at 5:24

1 Answer 1

0

You should be getting the number values of each position and add them using the power of 2 to get back the original number.

    double num = 1110;
    double ones = Math.floor(num % 10);
    double tens = Math.floor(num/10 % 10);
    double hundreds = Math.floor(num/100 % 10);
    double thousands = Math.floor(num %10000 /1000);
    double tenThousands = Math.floor(num / 10000 % 10);

    double original = (ones * 1) +
                      (tens * 2) + 
                      (hundreds * 4) +
                      (thousands * 8);


    System.out.println(num);
    System.out.println("ones: " +ones);
    System.out.println("tens: " +tens);
    System.out.println("hundreds: " +hundreds);
    System.out.println("thousands: " + thousands);
    System.out.println("original number : " + original);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chit, that works and I understand why its working and the math involved. Thank you again that was a big help as I was stuck on this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.