How to convert char to decimal using an ascii table? - java

I'm working on a java program to convert a 4 digit binary number to decimal. I need to enter the binary as a String, convert to a char, and then to a decimal. I cannot use something like:
int decimal = Integer.parseInt("1010", 2);
Here is my code so far:
import java.util.Scanner;
public class BinaryConvert2 {
public static void main(String[] args){
System.out.println("Please enter a 4 digit binary number: ");
Scanner s = new Scanner(System.in);
String binaryNumber = s.next();
char a, b, c, d;
a = binaryNumber.charAt(0);
a = (char) (a*2*2*2);
b = binaryNumber.charAt(1);
b = (char) (b*2*2);
c = binaryNumber.charAt(2);
c = (char) (c*2);
d = binaryNumber.charAt(3);
d = (char) (d*1);
System.out.println(binaryNumber + " in decimal is: " + a + b + c + d);
}
}
I'm trying to multiply the char values by powers of 2 so that it will convert to decimal, but when I run the program, I get weird answers such as :
Please enter a 4 digit binary number:
1010
1010 in decimal is: ?Àb0

The ascii (char) value of 0 is 48 and the value if 1 is 49,
so you need to subtract 48 from the value
a = binaryNumber.charAt(0);
int aInt = (a - 48) * 2 * 2* 2;
....
System.out.println(binaryNumber + " in decimal is: " + (aInt + bInt + cInt + dInt));

The problem is you are printing the a b c and d as chars so it will print what ever decimal value of a b c and d correspond to in the ascii table. If you want to print out decimals you will have to convert the value to decimal by subtracting 48 add them together and then print.
Has to be like this:
1010 = 8 + 0 + 2 + 0 = 10 then print 10. You are on the right track

get the numeric value and do multiplication, if you do with char it will use the ASCII value
int num = 0;
a = binaryNumber.charAt(0);
num += (Character.getNumericValue(a) * 2 * 2 * 2);
b = binaryNumber.charAt(1);
num += (Character.getNumericValue(b) * 2 * 2);
c = binaryNumber.charAt(2);
num += (Character.getNumericValue(c) * 2);
d = binaryNumber.charAt(3);
num += (Character.getNumericValue(d) * 1);
System.out.println(binaryNumber + " in decimal is: " + num);

Related

Jave - method is - parseByte(String s, int radix) - I can't understand it

This is an example the tutorial gives me. I cannot understand the answer - Parse byte value of 123 is 83 Parse byte value of -1a is -26. Please try to explain the method to me in a very simple way.
import java.lang.*;
public class ByteDemo {
public static void main(String[] args) {
// create 2 byte primitives bt1, bt2
byte bt1, bt2;
// create and assign values to String's s1, s2
String s1 = "123";
String s2 = "-1a";
// create and assign values to int r1, r2
int r1 = 8; // represents octal
int r2 = 16; // represents hexadecimal
/**
* static method is called using class name. Assign parseByte
* result on s1, s2 to bt1, bt2 using radix r1, r2
*/
bt1 = Byte.parseByte(s1, r1);
bt2 = Byte.parseByte(s2, r2);
String str1 = "Parse byte value of " + s1 + " is " + bt1;
String str2 = "Parse byte value of " + s2 + " is " + bt2;
// print bt1, bt2 values
System.out.println( str1 );
System.out.println( str2 );
}
}
The first value, 123, is interpreted as an octal number, i.e. a number with base 8.
Now 1 * 8^2 + 2 * 8 + 3 = 64 + 16 + 3 = 83
The second value, -1a, is interpreted as a hexadecimal number, i.e. a number with base 16. Due to the fact that we only have 10 symbols for digits (0, .., 9), the symbols a,b,c,d,e,f are used to represent digits with a decimal value larger than 9. So a(16) = 10(10), b(16) = 11(10) and so on.
And - (1 * 16 + 10) = -26
In your first example you take 123 and interpret it as a number in octal representation, that means the first digit is not 100 but only 64 (8*8). So 123 is interpreted as 8*8*1+8*2+3 = 83.
In the second example 1a is interpreted as in hexadecimal representation. So -1a = -(16*1+10) = -26.

Java Addition with characters [duplicate]

This question already has answers here:
Java: parse int value from a char
(9 answers)
Closed 6 years ago.
I am fairly new to java, about 3 weeks into my course. In my assignment, I needed to use charAt to separate the string into 14 parts. Now I need to use addition and add these together.
I have tried many times with no success. Every time I add them together and print it out it gives me a number way bigger than it should be.
char num1 = roulette.charAt(0);
char num2 = roulette.charAt(1);
char num3 = roulette.charAt(2);
char num4 = roulette.charAt(3);
char num5 = roulette.charAt(4);
char num6 = roulette.charAt(5);
When I add num1+num2+num3+num4+num5+num6, I get a number way bigger than it should be.
Am I missing something?
This is due to you adding the characters together, they will not turn into the number equivalent automatically. You will need to change them yourself, to do this you can use Integer.parseInt(char) and you can add them together like that. For example Integer.parseInt(String.valueOf('1') + Integer.parseInt(String.valueOf('2')) this will add 1 + 2 together correctly now resulting in 3 rather than appending 2 to the 1 making 12
If you want to add the characters then each character has a character code that will be used. so for example according to the ASCII Table 'a' = 97, 'b' = 98, 'c' = 99; so if you add these together you will get 294. ASCII Table https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html.
However, if each character represents a number and you want to add the numbers then you can do something like this:
char num1 = roulette.charAt(0);
int firstNum = Integer.parseInt(Character.toString(num1));
char num2 = roulette.charAt(1);
int secondNum = Integer.parseInt(Character.toString(num2));
char num3 = roulette.charAt(2);
int thirdNum = Integer.parseInt(Character.toString(num3));
char num4 = roulette.charAt(3);
int fourthNum = Integer.parseInt(Character.toString(num4));
char num5 = roulette.charAt(4);
int fifthNum = Integer.parseInt(Character.toString(num5));
char num6 = roulette.charAt(5);
int sixthNum = Integer.parseInt(Character.toString(num6));
int result = firstNum + secondNum + thirdNum + fourthNum + fifthNum + sixthNum;
You cannot cast your chars to integer first try like this
Integer.parseInt(num1) + Integer.parseInt(num2) +Integer.parseInt(num3)...
and so on.
EDIT
I just learned that you cannot use Integer.parseInt(num1) for Character.
You should cast your chars as below:
char a = '5';
int b = Integer.parseInt(String.valueOf(a));
int c=b+b;
System.out.println(c); //this will give 10
If you add characters to characters, it means you are adding their ascii values. But if you want to add the numeric value which is presented as a Character in the String, then you have to convert the character to integer first. See the example given below.
N.B. when you want to add a sequence of values, use loop.
Example
String roulette = "123456";
int sum = 0;
for (int i = 0; i < roulette.length(); i++) {
sum = sum + roulette.charAt(i);
}
System.out.println("Sum : " + sum);
sum = 0;
for (int i = 0; i < roulette.length(); i++) {
sum = sum + Integer.parseInt(String.valueOf(roulette.charAt(i)));
}
System.out.println("Sum : " + sum);
Output
Sum : 309
Sum : 21
Case 1: sum = sum + roulette.charAt(i);
Adding ascii values of the numbers. So the sum is 309.
ascii_value('1') - 49
ascii_value('2') - 50
...
ascii_value('5') - 53
ascii_value('6') - 54
Sum = 49 + 50 + 51 + 52 + 53 + 54 = 309
Case 2: sum = sum + Integer.parseInt(String.valueOf(roulette.charAt(i)));
Adding the numeric value instead of the ascii values. So the sum is 21.
Sum = 1 + 2 + 3 + 4 + 5 + 6 = 21

convert array numbers to negative

Java. I want to make an array of binary numbers available in negative form but I want the original positive binary numbers to remain there as well so I can use both positive and negative numbers in my program, but I can't find out a way to convert all the binary numbers I have in my array to negative binary numbers.
class Logicgates {
public static void main (String args[]) {
String binary[] = {
"0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"
};
int a = 3;
int b = 5;
int c = a | b; // 0010|0100 = 0110
int d = a & b; // 0010&0100 = 0000
int ff= a ^ b;
int f = ~((~a&b) ^ (~b | a));
int g = ~f | 0x0f;
System.out.println("a = " + binary[a]);
System.out.println("b = " + binary[b]);
System.out.println("c = " + binary[c]);
System.out.println("d = " + binary[d]);
System.out.println("ff = " + binary[ff]);
System.out.println("f = " + binary[f]);
System.out.println("g = " + binary[g]);
}
}
here the value of g is -1 but since my array only contains positive 1 I can't print it.
If you want to use your original array I completely understand, as it may be a requirement to your assignment / project / learning experience.
If not, Java actually has a built in function in the java.lang library that will convert a decimal number to a binary number. The output may not be exactly what you are looking for, so you may have to make a few changes.
import java.lang.*;
public static void main(String[] args) {
int positive = 14;
System.out.println("Positive Number = " + positive);
int negative = -14;
System.out.println("Negative Number = " + negative);
//to binary
System.out.println("Positive Binary is " + Integer.toBinaryString(positive));
System.out.println("Negative Binary is " + Integer.toBinaryString(negative));
}
The output for this snippet will be
Positive Number = 14
Negative Number = -14
Positive Binary is 1110
Negative Binary is 11111111111111111111111111110010
As you can see, the negative number outputs the entire 32-bit string, but it should be simple enough for you to trim it down to the size you are looking for (e.g. 4-bit or 5-bit).
With this approach you won't be required to have your array of binary strings. You can simply pass the number to the toBinaryString() function and it will convert it for you.
After that you just need to add your logic for the gates you are trying to simulate.
Hopefully this points you in the right direction. Good luck!

How to convert a binary String to a decimal string in Java

I was working on a homework and thought I had finished but the teacher told me that it wasn't what he was looking for so I need to know how I can convert a binary number that is stored as a String to a decimal string without using any built-in function outside of length(), charAt(), power function, and floor/ceiling in Java.
This is what I had on the beginning.
import java.util.Scanner;
public class inclass2Fall15Second {
public static void convertBinaryToDecimalString() {
Scanner myscnr = new Scanner(System.in);
int decimal = 0;
String binary;
System.out.println("Please enter a binary number: ");
binary = myscnr.nextLine();
decimal = Integer.parseInt(binary, 2);
System.out.println("The decimal number that corresponds to " + binary + " is " + decimal);
}
public static void main (String[] args) {
convertBinaryToDecimalString();
}
}
To convert a base 2 (binary) representation to base 10 (decimal), multiply the value of each bit with 2^(bit position) and sum the values.
e.g. 1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11
Since binary is read from right-to-left (i.e. LSB (least significant bit) is on the rightmost bit and MSB (most-significant-bit) is the leftmost bit), we traverse the string in reverse order.
To get the bit value, subtract '0' from the char. This will subtract the ascii value of the character with the ascii value of '0', giving you the integer value of the bit.
To calculate 2^(bit position), we can keep a count of the bit position, and increment the count on each iteration. Then we can just do 1 << count to obtain the value for 2 ^ (bit position). Alternatively, you could do Math.pow(2, count) as well, but the former is more efficient, since its just a shift-left instruction.
Here's the code that implements the above:
public static int convertBinStrToInt(String binStr) {
int dec = 0, count = 0;
for (int i = binStr.length()-1; i >=0; i--) {
dec += (binStr.charAt(i) - '0') * (1 << count++);
}
return dec;
}

How this bitshift to build the number works?

I saw this method which is used for faster reading of positive value of Long.
public static long readLong(InputStream in) throws IOException {
long n = 0;
int c = in.read();
while (c < 48 || c > 57) {
c = in.read();
}
while (c >= 48 && c <= 57) {
n = (n<<3) + (n<<1) + (c-'0');
c = in.read();
}
return n;
}
While I understand all of the part, what I'm not able to get is this:
bit shifting by odd number to
build the number n = (n<<3) + (n<<1) + (c-'0');
Why ignore the 3rd bit and how it's able to build it?
If anyone of you could explain me in simple way, it would be very much helpful.
Thanks!
n << i is n * 2^i. So,
(n<<3) + (n<<1) = (n * 2^3) + (n * 2^1) = n * (2^3 + 2^1) = n * 10
Basically, it means to shift the value of n one digit to the left.
Adding it with c + '0' means adding the last digit with the integer value of c.
Consider this code,
while (c >= 48 && c <= 57) {
n = (n<<3) + (n<<1) + (c-'0');
System.out.println(n);
c = System.in.read();
}
If I enter 123456, it prints
1
12 // 1 * 10 + 2
123 // 12 * 10 + 3
1234 // 123 * 10 + 4
12345 // 1234 * 10 + 5
123456 // 12345 * 10 + 6
So what it basically does is making space at the units place for the next number by just multiplying it by 10 and adding the int value of the character.
This is what happens:
(n<<3) means (n*8)
(n<<1) means (n*2)
(c-'0') gives you the character as int value
Together this means
n = n*10 + theNewDigit

Categories

Resources