Converting Decimal into binary in java - java

I am trying to convert decimal to binary numbers from the user's input using Java but so far, I'm running into errors I'm not sure why. What am I doing wrong? Don't mind the naming, ultimately I would like to convert decimal into binary without using if and while statements. Also without using the decimaltobinary string.
Thanks a lot.
package r
public static void main(String[] args) {
int number;
int remainder;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
remainder= number %2;
System.out.print(remainder);
{
return null;
This is what I have so far.

This is how to convert a decimal to binary :
Using for loop :
public class DecimalToBinary {
public void printBinaryFormat(int decimalNumber){
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
remainder = decimalNumber % 2;
decimalNumber /= 2;
System.out.print(remainder);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Using while loop :
public class DecimalToBinary
{
public void printBinaryFormat(int number){
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
}
public static void main(String a[]){
DecimalToBinary dtb = new DecimalToBinary();
dtb.printBinaryFormat(25);
}
}
Hope I helped .
Happy Coding :D

Try this:
String binaryString = Long.toBinaryString(Double.doubleToRawLongBits(yourDecimalNumber));
Where yourDecimalNumber is the name of the decimal variable that you want to convert to binary.
You can also use a for loop and bitwise operation without using any if or while statements like so:
int number = 10;
String binaryString = "";
final int intBitSize = 32; // 32 is the number of bits in an int.
for(int i=0; i<intBitSize; i++)
{
binaryString = String.valueOf(number&1) + binaryString;
number = number >>> 1;
}
System.out.println(binaryString);

Related

Convert a number of the datatyp String to char

I try to convert numbers of a String in to an array with the datatyp char. My problem is, that the number in my array is everytime 48 to high. I also know that the problem has something to do with ASCII table. What can i do to solve this problem?
package Test;
public class Main {
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber);;
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}
}
use
number[indexNumber] = calculation.charAt(iNumber) - '0';
Digit 0 has an ASCII value of 48. The range of ASCII value for 0-9 digits is from 48-57. So, whenever you extract a character, let's say '5', you store 53 instead of 5 in the array. So try to use the below code modification where you subtract character '0':
public static void main(String[] args) {
int iNumber = 0; int indexNumber = 0;
String calculation = "5+8";
int lengthCalculation = calculation.length();
int[] number= new int[lengthCalculation/2+1];
while(iNumber < lengthCalculation) {
number[indexNumber] = calculation.charAt(iNumber)-'0'; //modified
iNumber+=2;
indexNumber++;
}
for(int q : number) {
System.out.println(q); }
}

Finding the Sum of a String of numbers seperated by operators

Given String = "128+16+8+2+1"
Answer should print out 155
The code is supposed to add all numbers in the string and the answer should be printed out as a string.
I attempted to write the code for this, however the last 2 numbers will not add and my current answer is printing out 153. Looking for help to lead me to the correct solution.
import java.util.stream.*;
public class add {
static void evalA(String s) {
int n = countChar(s,'+');
System.out.println(s);
int cnt = 0;
int[] data = new int[n];
for(int i=0;i<s.length();i++) {
if (s.charAt(i)=='+') {
System.out.println(s.substring(0,i));
data [cnt] = Integer.parseInt(s.substring(0,i));
cnt++;
s = s.substring(i+1,s.length()-1);
i=0;
}
}
String sum = ""+IntStream.of(data).sum();
System.out.println(sum);
}
}
You could do something like this:
public static void main(String[] args)
{
evaluate("128+16+8+2+1");
}
public static void evaluate(String equation)
{
String[] numbers = equation.split("\\+");
int sum = 0;
for (String number : numbers)
{
//could wrap this in a check incase of exception or errors
sum += Integer.parseInt(number);
}
System.out.println(sum);
}
It just splits the string up by the + to get the individual numbers as an array and then loop through the array and add each numbers value to a sum variable.

Integer printing wrong value

When converting an integer to int array, for example 123 to {1,2,3}, I am getting values {49,50,51}.
Not able to find what is wrong with my code.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
Output:
49
50
51
charAt(i) will give you UTF-16 code unit value of the integer for example in your case, UTF-16 code unit value of 1 is 49.
To get integer representation of the value, you can subtract '0'(UTF-16 code unit value 48) from i.
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = temp.charAt(i);
}
for (int i : newGuess) {
System.out.println(i - '0');
}
}
}
Output:
1
2
3
To add a little Java 8 niceties to the mix which allows us to pack everything up neatly, you can optionally do:
int i = 123;
int[] nums = Arrays.stream(String.valueOf(i).split(""))
.mapToInt(Integer::parseInt)
.toArray();
Here we get a stream to an array of strings created by splitting the string value of the given integer's numbers. We then map those into integer values with Integer#parseInt into an IntStream and then finally make that into an array.
temp.charAt(i) is basically returning you characters. You need to extract the Integer value out of it.
You can use:
newGuess[i] = Character.getNumericValue(temp.charAt(i));
Output
1
2
3
Code
public class Test {
public static void main(String [] args) {
String temp = Integer.toString(123);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++) {
newGuess[i] = Character.getNumericValue(temp.charAt(i));
}
for (int i : newGuess) {
System.out.println(i);
}
}
}
As your interest is to get as an integer value of an string. Use the method parse int Integer.parseInt() . this will return as integer.
Example :
int x =Integer.parseInt("6"); It will return integer 6.

how to convert a string value to integer without using Integer.parseInt()?

I have this input like
String s = "6" , ss="99 , sss = "99999";
i need to store these values in an int reference variable ,
without using Integer.parseInt
any suggestion ? , no full code , just the hints ??
What about Scanner?
int a=new Scanner(s).nextInt();
Without util.
public static int parseInt(String s)
{
int ans=0;
for(int i=s.length()-1;i>=0;i--)
{
ans+=(s.charAt(i)-'0');
ans*=10;
}
return ans/10;
}
public class MyStringToNumber {
public static int convert_String_To_Number(String numStr){
char ch[] = numStr.toCharArray();
int sum = 0;
//get ascii value for zero
int zeroAscii = (int)'0';
for(char c:ch){
int tmpAscii = (int)c;
sum = (sum*10)+(tmpAscii-zeroAscii);
}
return sum;
}
public static void main(String a[]){
System.out.println("\"3256\" == "+convert_String_To_Number("3256"));
System.out.println("\"76289\" == "+convert_String_To_Number("76289"));
System.out.println("\"90087\" == "+convert_String_To_Number("90087"));
}
}
See more at this URL.
Try to get each char from the string and then the value of each char. 0 has a value of 48 so
char c = '9';
int i = c - 48;
Now i = 9. After that you only need to multiply this value with the appropriate power of 10 and add it to the total
public class ConvertIntoInt {
public static void main(String []args) {
String numStr = "3256";
char ch[] = numStr.toCharArray();
int sum = 0;
// Get ASCII value for zero
int zeroAscii = (int)'0';
for (char c:ch) {
int tmpAscii = (int)c;
System.out.println("Temp Ascii:" + tmpAscii);
sum = (sum * 10) + (tmpAscii - zeroAscii);
System.out.println(sum);
}
System.out.println(sum);
}
}

java random numbers generator which generate twenty four numbers

I want to create a program that gives a random 24 digit number. I have tried different ways but I can't figure out how to make it. An example response would be 392834756843456012349538, which is just a random twenty four digit number.
Here's the easiest way I can think of:
#Test
public void random24Numbers() {
String random = RandomStringUtils.random(24, false, true);
System.out.println(random);
}
This uses RandomStringUtils.random. The first parameter is the length, the second says, "no letters". The third says, "give me numbers". Here's an example output:
564266161898194666197908
Yes, it's a String, but I'm going to assume you know how to convert a String into a number.
This sample works for generating numbers of 'digits' length including leading zeros and doesn't require any external jar files.
private String generateInt(int digits) {
StringBuilder str = new StringBuilder();
Random random = new Random();
for(int i = 0; i < digits; i++) {
str.append(random.nextInt(10));
}
return str.toString();
}
An example response would be:
081140561664657769754888
The following uses only core java.lang stuff and seems to get the job done. As in other solutions, the result is a string rather than a java numeric type because none of the basic java datatypes can store 23-digit decimal numbers.
import java.lang.Math;
import java.lang.StringBuilder;
public class random24 {
static char digits[] = {'0','1','2','3','4','5','6','7','8','9'};
public static char randomDecimalDigit() {
return digits[(int)Math.floor(Math.random() * 10)];
}
public static String randomDecimalString(int ndigits) {
StringBuilder result = new StringBuilder();
for(int i=0; i<ndigits; i++) {
result.append(randomDecimalDigit());
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(randomDecimalString(24));
}
}
int[] randomNumbers = new int[24];
for(int i = 0; i < 24; i++) {
randomNumbers[i] = (int)Math.floor(Math.random() * 10);
System.out.println(randomNumbers[i]);
}
Added in response to the comment below, code to set a label with this random number sequence:
String randomString = "";
for(int i = 0; i < 24; i++) {
randomString = randomString.concat(String.valueOf((int)Math.floor(Math.random() * 10)));
}
NumbersLabel.setText(randomString);
See How to generate a random BigInteger value in Java? where code is provided which does generate a BigInteger random number not greater than n:
BigInteger r;
do {
r = new BigInteger(n.bitLength(), rnd);
} while (r.compareTo(n) >= 0);

Categories

Resources