Java-Bit Binary Number

  • Java
  • Thread starter J.live
  • Start date
  • #1
95
0

Main Question or Discussion Point

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:

Answers and Replies

  • #2
33,505
5,191
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.
 
  • #3
595
0
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.
 
  • #4
297
2
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.
 
  • #5
95
0
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?
 
  • #6
297
2
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:

http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String, int)

It really trivializes the whole thing, doesn't it?
 
  • #7
33,505
5,191
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.
 
  • #8
95
0
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.
 
  • #9
297
2
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.
 
  • #10
33,505
5,191
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
 
  • #11
297
2
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.
 
  • #12
95
0
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:
  • #13
297
2
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.
 
  • #14
95
0
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.
 
  • #15
33,505
5,191
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.
 
  • #16
95
0
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:
  • #17
297
2
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.
 
  • #18
33,505
5,191
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.
 
  • #19
95
0
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:
  • #20
297
2
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?
 
  • #21
33,505
5,191
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.
 
  • #22
95
0
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.
 
  • #23
297
2
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.
You probably should read this page describing what is meant by "an expression" in programming:

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'.
 
  • #24
95
0
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.
 
  • #25
33,505
5,191
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.
 

Related Threads on Java-Bit Binary Number

  • Last Post
Replies
6
Views
8K
Replies
2
Views
3K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
2
Views
1K
Replies
30
Views
2K
Replies
2
Views
3K
Replies
7
Views
6K
Replies
8
Views
2K
Top