0

Hi all I am trying to write an encryption program which converts each letter of the input to a 7 byte binary number before outputting. I am using the .toBinaryString method for this so please do not suggest another solution, the problem I am having is that it only converts the first character of the string! any help is appreciated here is my attempt

public static void convert(String h)
{
    int y =0;
    String f =" ";

    for(int i =0; i<h.length(); i++)
    {
         y = (int)h.charAt(i);
        f = Integer.toBinaryString(y);
    }

    System.out.println(y);
    System.out.println(f);
}

I print out y,f to see is it successfully converts it. It works when I input a single character but when I input eg ben it will convert the whole string not letter by letter!

1
  • Pedantic aside: Each character of the input already is a 16-bit (not byte) binary number. You're converting each letter to a string that's a textual representation of said number. Commented Feb 11, 2013 at 22:18

2 Answers 2

4

You are assigning a new string to f on each iteration, so you are left with the last character. You rather need to update the existing string each time.

So, use:

f += Integer.toBinaryString(y);

in place of:

f = Integer.toBinaryString(y);

Apart from that, consider using a StringBuilder, since you are manipulating string inside a for loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahhh Dam I can't believe I missed that! Thank you!
@user1816464. Happens sometimes. But take my last suggestion seriously.
0

What about just:

String h.....
bytes[] bytesArray = h.getBytes();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.