# Java-Bit Binary Number

• Java
J.live
Question:
Write a program that reads a four-bit binary number from the keyboard as a string and then converts it into decimal. For example if the input is 1100 the output should be 12.

Attempt:
Code:
import java.util.Scanner;

public class run

{
private static final String number = null;

public static void main(String[] args)
{

int number;
String value;

Scanner keyboard = new Scanner (System.in);
System.out.print("Enter Number");

number=keyboard.nextInt();
value=""+number;// concatenated integer number to string value.
value=value.substring(0,1);// How do I convert this substring to a value of bit?

}

}

This code is incomplete as I am not sure how to go about it.

I think, I know how to convert binary number to decimal. You just multiply each number by the base of 2 depending on which place the number holds. Then add up the numbers to get a total ?

Basically, I am having trouble assigning String to number and then splitting it into substrings. How do I do the calculation with each substrings? I'll appreciate if someone could help me out with the code. Thanks.

Last edited:

Mentor
Notice that the directions say to "read(s) a four-bit binary number from the keyboard as a string..." So number should be a string, not an int. Also, you have way more variables than you need. You don't need individual variables for the digits. Use the elements of the string.

You're probably going to want to use a loop to do this, and work your way from the back of the string of bits to the front.

As far as operators go, Java adheres fairly closely to C and C++, so there is no ^ operator for exponentiation. There is a ^ operator, but it is used for something else (exclusive OR). To raise a number to a power, which you don't really need for this problem and shouldn't use, there is the double pow(double, double) method that is in the Math class.

schip666!
Rather than the pow() method, which is rather general, because you are dealing with binary numbers you could just shift your value up by one bit each time:

value <<= 1;

Try it out and see what it does.

Grep
You're got the mathematical part now. The shifting schip666! told you about is the way to do it. Just put a 1 into the variable when you check the first bit. If it's set, add it to a running total (make sure to initialize it to 0 before you start).

What you're missing is reading the bits. Forget substring. What you need is charAt (on a String as Mark said). You'll probably want to go through the string backwards. Say you're using index 'i' which is set to the last index in the string. Then something like this:
Code:
if (line.charAt(i) == '1')
{
// SET BIT
}
You should be able to put it together fairly easily at this point. You just need to loop over each bit and set it or not, depending on the result of charAt.

J.live
The problem is , he is not letting me use loop for this problem.

Grep- is there a way to implement charAT in the method without the use of loop?

Grep
The problem is , he is not letting me use loop for this problem.

Grep- is there a way to implement charAT in the method without the use of loop?
Yes, but it's probably a bad idea to do it that way. You would have to hard code each bit check. I doubt that's what your teacher intends.

Rather, it seems to me he wants you to learn how to do it with the existing Java API. In which case, there's a much easier way to do it. It's in the Integer class:

It really trivializes the whole thing, doesn't it?

Mentor
J.live,
Are you told not to use the for loop specifically, or loops in general? If it's just the for loop that you can't use, there are other loops besides the for loop.

J.live
Mark-not to use loops in general. Since this is like the first chapter. He introduced us to loops today.

Grep- where exactly do I go on that page? binaryString?

He told me to use charAt or go about converting each substring to a value of bit.

Grep
Mark-Not to use loops in general. Since this is like the first chapter. He introduced us to loops today.

Grep- where exactly do I go on that page? binaryString?

He told me to use charAt or go about using converting each to substrings.
It should bring you right to it. It's the parseInt method with a String and a number as parameters.

Got to say, I'm a little confused with your teacher. Without a loop, you end up writing really, frankly, dumb code. And if you handle a variable number of binary digits, it introduces other problems since you'll have to do a variable number of such operations.

For example, you might end up with something like this (assuming the least significant bit is at index 31 - a huge assumption):
Code:
int flag = 1;
int value = 0;
if (line.charAt(31) == '1')
{
value += flag;
}
flag <<= 1;
if (line.charAt(30) == '1')
{
value += flag;
}
... etc ...
You'd have to do that 32 times if you want to handle 32 bits. Like I said, kinda dumb. Nobody would actually write a program like that.

Can't think of another way to use charAt and not use a loop. But I fail to see what you would learn from doing it this way. Or using parseInt, for that matter.

Mentor
Since you will be working with a string of at most four characters, a loop isn't absolutely necessary. You can just go through the values in the string and build up the number that the string represents.

For example, if the input variable's name is value, and the input string is "1010" then
value.charAt(0) is '1' and the multiplier is 8, so for this place we get 1 * 8 = 8
value.charAt(1) is '0' and the multiplier is 4, so for this place we get 0 * 4 = 0
value.charAt(2) is '1' and the multiplier is 2, so for this place we get 1 * 2 = 2
value.charAt(3) is '0' and the multiplier is 1, so for this place we get 0 * 1 = 0

The grand total is 8 + 0 + 2 + 0 = 10

Grep
Since you will be working with a string of at most four characters, a loop isn't absolutely necessary.
I missed that. Yeah, with 4 bits it's not as silly as I thought.

J.live
So, something like this

Code:
int value;

String number;

System.out.print("Enter Number");

number=keyboard.nextLine();

value=number.charAt(0)*8;

System.out.println(value);

Output:

Enter number 1

392

Grep- I get what you are saying. I guess, very soon, we will embark on problems using loops .

P.S. How do I multiply the base to each integer?

So, I still have to use the if statement ?

Last edited:
Grep
So, something like this

Code:
int value;
String number;

System.out.print("Enter Number");

number=keyboard.nextLine();

value=number.charAt(0)*8;

System.out.println(value);

Output:

Enter number 1

392

Grep- I get what you are saying. I guess we will embark on problems using loops very soon.

P.S. How do I multiply the base to each integer?

So, I still have to use the if statement ?
You'll need the if, yes. Because the value of charAt(0) is a 1 or a 0 *character*. It has a numerical value that is not 1 or 0. So you would need to check if it's a 1 character, then add the value of that bit to a running total if it is.

Note that you can add to a variable like this:

value = value + 8;

Or use the shorthand:

value += 8;

Next bit would be worth 4, and so on. You don't need to initialize the variable to 0 if you assign the way you have on the first (most significant) bit. But you'll need to add to the variable and not just assign for the other 3 bits processed after.

Also, since you're expecting 4 bits, you might want to make sure you got exactly 4 characters. You could also check to see if they're all 1 and 0 characters, but at minimum make sure you got exactly 4 characters. Something like:
Code:
if (keyboard.length() != 4)
{
System.out.println("Please enter exactly 4 binary digits.");
}
else
{
// You have 4 digits, so do your thing here
}
Not sure if your teacher expects any error handling at this point, so it's up to you if you check. Wouldn't think so, but a real program would check.

J.live
Thanks Grep.

I don't know, because we haven't even touched on if statement till now. This problem is from chapter 2. He goes by the book. He wants us to use the information in chapter 2 only to figure the problems out. I showed him what we did last time and he rejected it. So, I don't know how he expects us to do it without the use of if statement or loop. Perhaps, substrings? Sorry for bugging you time and again. It's just very frustrating.

Mentor
This would work.
Code:
.
.
.
value = 0;
value = value + (charAt(0) - '0')*8;
value = value + (charAt(1) - '0')*4;
value = value + (charAt(2) - '0')*2;
value = value + (charAt(3) - '0')*1;
.
.
.

charAt(n) will evaluate to either '0' or '1', which have ASCII codes of 48 and 49.
By subtracting the character '0', I am really subtracting 48.
If charAt(n) == '0', the expression charAt(n) - '0' evaluates to 0.
If charAt(n) == '1', the expression charAt(n) - '0' evaluates to 1.

J.live
Thank you, Mark.

Here is what I did.

Code:
int value,sum,t,x,y,z;
String number;

System.out.print("Enter Number");

number=keyboard.nextLine();

value=0;

t=value=value+ (number.charAt(0) - '0')*8;
x=value=value+(number.charAt(1)-'1')*4;
y=value=value+(number.charAt(2)-'2')*2;
z= value=value+(number.charAt(3)-'3')*1;

sum= t+x+y+z;
System.out.println(sum);

Output:

Enter Number1100
21

Shouldn't it be 12? Don't know what I did wrong here.

Oh shoot. "value "isnt reading any number. So it's coming out wrong

The program has to read the binary number as a string from the keyboard.

Last edited:
Grep
Go read Mark's post again, carefully. It fully and clearly explains the charAt(0) - '0' thing. If you understand what's going on, one of your mistakes should become really obvious.

Another thing is that you don't need those extra variables you use. Mark's code was already fine. Make sure you understand how to add something into an existing variable. For example, adding 42 to whatever is already in 'value':

value = value + 42;

Which can also be written as:

value += 42;

Follow along closely. That first one takes whatever is in 'value' and adds 42 to it. It then assigns the result to the variable 'value'. Thus, adds 42. The other way is just a shorthand. Note that you should make sure to initialize the variable in some way before you do that. Setting it to 0 is a good way, as Mark did.

If you understand both those things, the mistakes you made should be apparent.

Mentor
What you did wrong was add in a bunch of variables that aren't needed, and they screwed up the calculation. Get rid of t, x, y, z, and sum. You need only two variables: number and value.

J.live
Code:
int value;
String number;

System.out.print("Enter Number");

number=keyboard.nextLine();

value=0;
value=value + (number.charAt(0)-'0')*8;
value=value + (number.charAt(1)-'1')*4;
value=value + (number.charAt(2)-'2')*2;
value=value+ (number.charAt(3)-'3')*3;

System.out.println(value);

Output:

Enter Number1100
-5

I got rid of the extra variables. I understand that it is adding to the value. But the keyboard is reading "number" not value. So,does that mean value holds no integer? How is it deriving to -5 ? I am not sure about what goes in the last print line "System.out.println (value)" either.

Last edited:
Grep
You're still not understanding what Mark posted. As I said:
Go read Mark's post again, carefully. It fully and clearly explains the charAt(0) - '0' thing. If you understand what's going on, one of your mistakes should become really obvious.
What Mark said, and it's important, so understand it, is this:
charAt(n) will evaluate to either '0' or '1', which have ASCII codes of 48 and 49.
By subtracting the character '0', I am really subtracting 48.
If charAt(n) == '0', the expression charAt(n) - '0' evaluates to 0.
If charAt(n) == '1', the expression charAt(n) - '0' evaluates to 1.

Something still wrong? I am not sure about what goes in the last print line "System.out.println (value)" either.

So yes, you've introduced an error, and the answer is still wrong. Keep in mind what Mark said, and look at these lines:

Code:
value=0;
value=value + (number.charAt(0)-'0')*8;
value=value + (number.charAt(1)-'1')*4;
value=value + (number.charAt(2)-'2')*2;
value=value + (number.charAt(3)-'3')*3;
Why would you subtract '3', '2' or '1' at any point in this?

Lastly, a *1 has somehow become a *3. Why? You do understand why we've got *8, *4 and *2 on preceding lines, right?

Mentor
Formatting fix.
Code:
int value;
String number;

System.out.print("Enter Number");

number=keyboard.nextLine();

value=0;
value=value + (number.charAt(0)-'0')*8;
value=value + (number.charAt(1)-'1')*4;
value=value + (number.charAt(2)-'2')*2;
value=value+ (number.charAt(3)-'3')*3;

System.out.println(value);
The code above is still wrong, as Grep points out. All I did was make the indentation uniform. As it was, the code was drifting off to the right for no good reason.

J.live
Sorry about the *3 in the last line. I just noticed it.

Subtracting? I thought that was an expression ? As Mark stated on the previous page

If charAt(n) == '0', the expression charAt(n) - '0' evaluates to 0.
If charAt(n) == '1', the expression charAt(n) - '0' evaluates to 1.

Grep
Sorry about the *3 in the last line. I just noticed it.

Subtracting? I thought that was an expression ? As Mark stated on the previous page
He also said:
Mark44 said:
By subtracting the character '0', I am really subtracting 48.

http://en.wikipedia.org/wiki/Expression_(programming)

So this is an expression, for example:

value + (charAt(0) - '0')*8

For that matter, so is 2+2. As is charAt(0) - '0'.

J.live
Code:
int value;
String number;

System.out.print("Enter Number");
number=keyboard.nextLine();
number=keyboard.nextLine();

value=0;
value= value+(number.charAt(0)-'0')*8;
value=value+(number.charAt(1)-'0')*4;
value=value+(number.charAt(2)-'0')*2;
value=value+(number.charAt(3)-'0')*1;

System.out.println(value);

Output:

Enter Number1100
12

So, it's basically subtracting each value by 0= 48. Then multiplying it by the base.

I feel stupid for not noticing and understanding something so obvious. Thank you both of you for being to so patient with me.

Mentor
Code:
int value;
String number;

System.out.print("Enter Number");
number=keyboard.nextLine();
number=keyboard.nextLine();

value=0;
value= value+(number.charAt(0)-'0')*8;
value=value+(number.charAt(1)-'0')*4;
value=value+(number.charAt(2)-'0')*2;
value=value+(number.charAt(3)-'0')*1;

System.out.println(value);

Output:

Enter Number1100
12

So, it's basically subtracting each value by 0= 48.
Not quite. It's subtracting '0' (which has a value of 48). '0' is different from 0. One is the character for zero, and the other is the number zero.

What each line is doing is multiplying some power of 2 by either 0 or 1, and then adding the resulting value onto value.

It would probably be helpful for you to pretend to be the computer, and going through each line and figuring out exactly what happens. This is really the only way to be able to write code - by understanding exactly what each line of code does.
Then multiplying it by the base.

I feel stupid for not noticing and understanding something so obvious. Thank you both of you for being to so patient with me.

Grep
So, it's basically subtracting each value by 0= 48. Then multiplying it by the base.

I feel stupid for not noticing and understanding something so obvious. Thank you both of you for being to so patient with me.
There we go, you got it! And you're welcome. These things get easier after a bit. That is, as long as you make sure to understand things as you go through them. Otherwise, it gets a lot harder. I suspect you're learning a lot at this point.

Oh yeah, one small error. You're reading the string in twice. That line somehow got doubled. But that's what I call an easy one to fix.

Grep
It would probably be helpful for you to pretend to be the computer, and going through each line and figuring out exactly what happens. This is really the only way to be able to write code - by understanding exactly what each line of code does.
Some of the best advice you'll ever get about programming, right there. Frame it, live it, make it a part of you. :rofl:

Mentor
Here's the code with the extra input line removed, and using the += operator, plus the addition of some white space for better readability.
Code:
int value;
String number;

System.out.print("Enter Number ");
number = keyboard.nextLine();

value=0;
value += (number.charAt(0) - '0') * 8;
value += (number.charAt(1) - '0') * 4;
value += (number.charAt(2) - '0') * 2;
value += (number.charAt(3) - '0') * 1;

System.out.println(value);

J.live
Lol, Grep. Yeah, sure will try to swear by Mark's advise. Yeah, I am trying to retain as much information possible from here.

Quick question: In the very last line " System.out.println(value);" I threw in value to be printed out. Do all the characters add with each other vertically? Since they are lined up vertically. Usually in order to add up to a total , isn't it like : sum= a+b+c? Then we print out the int sum?

Last edited:
Grep
Quick question: In the very last line " System.out.println(value);" I threw in value to be printed out. Do all the characters add with each other vertically? Since they are lined up vertically. Usually in order to add up to a total , isn't it like : sum= a+b+c? Then we print out the int sum?
Nope, no such requirement. Those lines just keep modifying an existing variable. Mind you, you could also just do this:
Code:
value = ((number.charAt(0) - '0') * 8) + ((number.charAt(1) - '0') * 4) + ((number.charAt(2) - '0') * 2) + (number.charAt(3) - '0');
They both work out to the same thing. Though note that I took out the last *1 since it's obviously not needed (but it was good to make it explicit when explaining things to you). Personally, I'd format that line as:
Code:
value = ((number.charAt(0) - '0') * 8)
+ ((number.charAt(1) - '0') * 4)
+ ((number.charAt(2) - '0') * 2)
+ (number.charAt(3) - '0');
Breaking it up onto different lines in this manner changes nothing. As far as the compiler is concerned, it's all one line until it hits the semi-colon. A space and a newline character are all treated the same by the compiler: as whitespace. But it makes it more readable for you and I.

All this put another way,
Code:
sum = a + b + c;
could be written as:
Code:
sum = a;
sum += b;
sum += c;
There may be a good reason to do it one way or the other, but they both end up with the same result. In some cases, though, you'll want to use 'sum += '. For example, we could use an array of numbers instead of a, b and c. Then we can use a for loop, and it will add any number of numbers together.

Assuming an array of integers called 'numbers':
Code:
int sum = 0;
for (int i = 0; i < numbers.length; i++)
{
sum += numbers[i];
}
System.out.println("The sum of the numbers is " + sum);
Since numbers.length would be the number of elements in the array, we can iterate over it that many times, adding the current number (at index i) to our running total.

mango22223
hey J.live
I am currently working on this problem as well. I've tried your code but i keep getting an error for the code line:

number=keyboard.nextLine();
number=keyboard.nextLine();

do you know why by any chance?

mango22223
Here's the code with the extra input line removed, and using the += operator, plus the addition of some white space for better readability.
Code:
int value;
String number;

System.out.print("Enter Number ");
number = keyboard.nextLine();

value=0;
value += (number.charAt(0) - '0') * 8;
value += (number.charAt(1) - '0') * 4;
value += (number.charAt(2) - '0') * 2;
value += (number.charAt(3) - '0') * 1;

System.out.println(value);
hey Mark44
I am currently working on this problem as well. I've tried your code but i keep getting an error for the code line:

number=keyboard.nextLine();
number=keyboard.nextLine();

do you know why by any chance?

Mentor
Why do you have two lines there?

Show us your code and I'm sure we can figure it out.

mango22223
my codes are:

import java.util.Scanner;

public class project11p117 {
Scanner input = new Scanner(System.in);
public static void main(String [] args){

int value;
String number;

System.out.print("Enter Number");
number=keyboard.nextLine();

value=0;
value= value+(number.charAt(0)-'0')*8;
value=value+(number.charAt(1)-'0')*4;
value=value+(number.charAt(2)-'0')*2;
value=value+(number.charAt(3)-'0')*1;

System.out.println(value);

}
}

mango22223
my codes are:

import java.util.Scanner;

public class project11p117 {
Scanner input = new Scanner(System.in);
public static void main(String [] args){

int value;
String number;

System.out.print("Enter Number");
number=keyboard.nextLine();

value=0;
value= value+(number.charAt(0)-'0')*8;
value=value+(number.charAt(1)-'0')*4;
value=value+(number.charAt(2)-'0')*2;
value=value+(number.charAt(3)-'0')*1;

System.out.println(value);

}
}