2

I need to convert ASCII characters to (7-bit) binary. I have seen this, but it gives me the binary value in 8 bits, meanwhile i want it to be in 7 bits. For instance:

C should be 1000011

CC should be 10000111000011

% should be 0100101

So, I changed the code to:

String s = "%";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (int j = 0; j < 7; j++) {
    int val =  bytes[j];
    for (int i = 0; i < 8; i++) {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
    }
    binary.append("");
}

System.out.println("'" + s + "' to binary: " + binary);

and it complains with:

java.lang.ArrayIndexOutOfBoundsException: 1

in the line:

int val =  bytes[j];

To highlight:

I used

 for(int j=0;j<7;j++)
    int val =  bytes[j];

instead of

for (byte b : bytes) int val = b;

2
  • "%".getBytes() is returning bytes, not bits. Your bytes array will only have 1 element in it (at index 0). Commented Jan 18, 2017 at 15:33
  • byte, being integer types IS BINARY. You want not convert, but print it in binary form Commented Jan 18, 2017 at 15:36

3 Answers 3

3

Change your first for loop from:

for (int j = 0; j < 7; j++) {

To:

for (int j = 0; j < bytes.length; j++) {

You want this outer loop to loop over all of the elements of bytes.

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

Comments

2

There are 2 changes in your code below :

        String s = "%";
        byte[] bytes = s.getBytes();
        StringBuilder binary = new StringBuilder();
        for (int j = 0; j < bytes.length; j++) {
            int val = bytes[j];
            for (int i = 0; i < 7; i++) {
                val <<= 1;
                binary.append((val & 128) == 0 ? 0 : 1);
            }
        }

        System.out.println("'" + s + "' to binary: " + binary);

Comments

0

Here is some code which should give you a hint; it takes each character as a byte, then walks along each of the least significant 7 bits, using a bitmask. Just add your string builder code;

public static void main(String[] args) {
    String s = "A";
    byte[] bytes = s.getBytes();

    for (int bytePos = 0; bytePos < bytes.length; ++bytePos) {
        byte b = bytes[bytePos];
        byte mask = 0b1000000;
        while (mask > 0) {
            System.out.println(b & mask);
            mask /= 2;
        }
    }
}

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.