Alright, so I am building a Converter to convert ASCII to Binary and for some reason, the for each loop stops working when it hits a space, and I have no idea why. I'm probably just over thinking it.

Extra: Can you tell me how to force the output binary to be 8 chars? So add 0's to the front until the length is 8.

package com.github.geodox.asciitobinary.main;

import java.util.Scanner;

public class ASCIItoBinary
{
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args)
    {
        getInput();
    }

    private static void getInput()
    {
        String repChar;
        String inputString;

        log("Please Enter a Character to Represent a Space: ");
        repChar = input.next();

        if(repChar.length() < 1 | repChar.length() > 1)
        {
            logln("Character Length is invalid. Please Enter a Single Character.");
            getInput();
        }

        log("Please Enter a String to convert to Binary: ");
        inputString = input.next();

        convertToBinary(repChar, inputString);
    }

    private static void convertToBinary(String repChar, String inputString)
    {
        String outputString = "";

        for(char c : inputString.toCharArray())
        {
            if(c != ' ')
            {
                outputString = outputString + " " +  Integer.toBinaryString((int) c);
            }
            else
            {
                outputString = outputString + " " + repChar;
            }
        }

        outputString = outputString.trim();
        outputBinary(outputString);
    }

    private static void outputBinary(String outputString)
    {
        log(outputString);
    }

    public static void log(Object aObject)
    {
        System.out.print(aObject);
    }

    public static void logln(Object aObject)
    {
        System.out.println(aObject);
    }

}

Recommended Answers

All 14 Replies

"stops working" means what exactly?

You can force leading zeros by
a) prepending eights zeros, then substring the last 8 chars of the result
or
b) add 256 to the value before converting to a binary string, then drop the first character
or
c) probably lots of other ways?

ps line 22 should probably be a while, not a single-pass if

pps: You have fallen into the trap of thinking of Java chars as ASCII. They are not. ASCII is a 7 bit code with just English letters. Java chars are 16 bits and encode letters from all kinds of languages and scripts (including English letters, which have the same values as in ASCII). If you assume ASCII then your code will fall over as soon as it hits a letter that's not an un-accented A-Z.

Example inputString
Hello, my name is Bob.
Example outputString
Binary of first letters up to the first space.

Will this still work? Or should I approach this in a completely different way? Or limit it to just English Characters and Special Characters?

Sorry, that's still not clear to me. Can you post an actual small example of an input/output pair? Is it like this?:
in: "ab c"
out: "01100001 01100010"

In that case you just

loop through the characters of the string
  if it's a space then break
  check that it's <=255
     convert to binary string (see previous post for leading zeros)
     append that to output string
return the string

Based on your previous threads I can't see why you are having any problem with something so simple!

This is a solution on how you could solve you problem, I m again working in java a little bit so I m trying to get the syntax to my brain so I hope that people won't get mad for posting the solution...

public class Solution
{

    public static void main(String[] args) 
    {
      Scanner sc=new Scanner(System.in);
        String concat="";
        String input = sc.nextLine();
        char [] array=input.toCharArray();
        for(int i =0;i<array.length;i++)
        {
            int z=(int)array[i];
            String binary=decToBin(z);
            concat=concat+CheckNumbersOfDigits(binary);
            concat+="-";

        }
       out.println(removeLastChar(concat));
    }
    private static String CheckNumbersOfDigits(String digit) 
    {

        int diglen=digit.length();
        int add_dig=8-diglen;
        for(int i=0;i<add_dig;i++)
        {
            digit="0"+digit;
        }
        return digit;
    }
    public static String decToBin(int dec) 
    {
        if (dec == 0) {
            return "0"; // special case
        }

        final StringBuilder result = new StringBuilder();
        int current = dec;

        while (current != 0) {
            result.append(current & 0x1);
            current = current >> 1;
        }

        return result.reverse().toString();
    }
    private static String removeLastChar(String str) {
        return str.substring(0,str.length()-1);
    }

 }

Here at DaniWeb we try to help people learn Java and develop their Java skills. We do NOT do people's homework for them. Your post explains and teaches nothing, it just gives the OP a chance to cheat. In future please help by pointing people in the right direction - eg tell them which classes and methods they should read about, or give them some sample code that they will have to understand and adapt to their needs. If you feel you should correct someone's code then that's useless if you don't explain what you changed and why you changed it as you did. If you need to explain with actual code then explain why you coded it the way you did. Don't just spoon-feed them a solution to copy and paste.

commented: you are right +4

It's a good thing it's not home work :P
James, I don't want the loop to break on a space, I want it to add the repChar to the outputString. I was trying to say that what it is doing now is breaking at the space.

I don't understand - what do you mean by "breaking at the space"? All your code does is to replace the space in the output by whatever repChar was input earlier. In what sense does that "break"?

It does exactly what I said before.
If I enter - in for repChar
And Hello, my name is Doogledude123 for the inputString
All I get in outputString is
01001000 01100101 01101100 01101100 01101111 00101100

You may nor want to read this post, because the embarassment will be hard to bear...

You get the input string via inputString = input.next(); which reads the next token. Tokens are delimited by the default of a blank. You never read the rest of the line. I hate Scanner.

What would you use? I honestly didn't know that :P

Personally I hate Scanner. It's amazing how often we get threads here where people have mixed nextInt's and nextLine's and can't understand why it's not working. It was intended to be an easy thing for beginners, but it has too many odd behaviours to be safe.
My preference is always to use a BufferedReader to read whole lines from the console...

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
inputString = in.readLine();

... then parse the contents as necessary using split, Integer.parseInt etc etc

Thanks guys! Got it working now!
Will keep in mind about Scanner, and probably won't use it again unless I have to!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.